On Thu, May 28, 2009 at 11:06 AM, Max Williams
<[email protected]> wrote:
>
> I've got a form for editing a model called Property.  Property has two
> fields, web_color and thumbnail_path, that are nil by default, and the
> model has some behaviour to generate defaults for them when nil, which
> is the usual case.
>
> When the form is submitted, the text fields for these attributes come
> through as empty strings, and so these attributes are changed to be
> empty strings instead of nil.
>
> I can think of some hacky ways to stop this, such as doing something
> like this in the controller:
>
> params[:property][:web_color] = nil if
> params[:property][:web_color].blank?
>
> But, it would be better if this behaviour lived in the model.  One way
> would be to set up a before_save callback like this:
>
> before_save :set_nils
>
> def set_nils
>  self.web_color = nil if self.web_color.blank?
>  self.thumbnail_path = nil if self.thumbnail_path.blank?
> end
>
> But, this feels kind of hacky and i'd like a cleaner way.  Can anyone
> show me one?
>
> thanks
> max
> --

In your model do

def web_color(web_color)
  web_color = nil if web_color.blank?
  write_attribute(:web_color, web_color)
end

and the same for thumbnail_path

Andrew Timberlake
http://ramblingsonrails.com

http://MyMvelope.com - The SIMPLE way to manage your savings

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to