TopperH
TopperH

Reputation: 2223

How to trigger a "completed" attribute when a form is complete?

I have a rails model that is filled by a very long form (split using the wicked-wizard gem).

There are some validations but I allow blank in most of the fields.

I need to take certain actions if the model is saved but some of the fields remain blank (for example remember the user to complete the form)and some other actions if the form 100% complete (for example sending the user an email to let him know the form is complete).

My idea is to trigger a virtual attribute such as :complete if there are not blank fields in my model, but I'm not sure how and where to do that.

Any hints?

========================= EDIT

Thanks to @Kzu suggestion I've found this to work on my wizard controller (but could also work on the object controller itself)

  def update
    @customer = current_user.customer
    params[:customer][:complete] =  @customer.attributes.select{|key,value| value.nil? or !value.present? }.any?  ? false : true
    @customer.attributes = params[:customer]
    render_wizard @customer
  end

Upvotes: 2

Views: 95

Answers (1)

Kzu
Kzu

Reputation: 783

For example you can use an ActiveRecord callback and a complete boolean field for this form.

before_save :check_if_complete
def check_if_complete
    # self.attributes returns a hash including the attribute name as key and its value as value
    completion = self.attributes.select{|key,value| value.nil? or value.blank?} ? false : true
    self.complete = completion
end

This solution could work but take care of the different attribute types you have in database.

Upvotes: 1

Related Questions