Helpful Information
 
 
Category: Ruby Programming
Calling model methods even when the param is a not set

Hello,
I'm setting a checkbox values based on the return of a model field method. The way the method is set up - it only gets called when a checkbox value is set.

Here's the model code:



def within=(new_within)
@within = new_within == "1" || new_within == true || new_within == 'true' || new_within == 'on'
end


I would like that method to be called even when the checkbox is not set.

Thanks for any help anyone can provide.

Clem C

You're not going to get that method called when the value is not set in the checkbox. That's because the HTTP protocol will not send the field value if the checkbox is not set. The solution is to

1. Set the underlying model's default value to 0 for the field, so when you create a new instance, the default is set.

2. Check if model.within is set after you've set the other values and then set it yourself, if it isn't:


model = Model.new(params[:model])
if model.within.nil?
model.within = 0
end
model.save


3. Override the new method for your model and make it set the value of model.within first before updating with all the passed in params.










privacy (GDPR)