I have a belongs_to relationship that can be removed without destroying either the parent or the child (transfer_form). Users can eliminate the parent relationship by selecting the blank option in a select dropdown while editing. Unfortunately, when they do this, I end up with
NoMethodError: undefined method `id' for "":String
Unless I perform a check on my parameters.
The following works but smells bad. Is it possible to move my current_school check to my model? Is this something I should do or should I leave it in my controller?
def update
@transfer_form = TransferForm.find(params[:id])
t = params[:transfer_form]
if t['current_school'] == ""
t['current_school'] = nil
end
respond_to do |format|
if @transfer_form.update_attributes(t)
...
end
end
You could always just do
params['current_school'] = nil if params['current_school'].blank?
but in reality the best practice would be to validate it in your model and do something like:
validates :current_school, :allow_blank => false
Then when you save it with an empty string it will error out, but I'm guessing you just want to set it to nil.
Update
I think its fine in your controller, but if you really want it in your model I would just use a before_save callback, that way you don't have any code in your controller, it will just automatically set every empty string to nil:
(untested)
before_save :sanitize_school
def sanitize_school
current_school = nil if current_school.blank?
end