Ruby on Rails Sunday, June 8, 2014

On Sunday, June 8, 2014 2:17:08 AM UTC+1, Asa Romberger wrote:

>   attr_accessor :attrvalue

> The dbvalue works, the attrvalue does not work and always throws the message attrvalue is not a valid response.
>
> I assume that attrvalue is not a boolean. Can I force it to be a boolean? Alternately, is there another way to handle it?

Forms always submit strings, so the value that ends up in your model is the string "true" rather than he boolean true. For the dbvalue the accessors activerecord provides know that the corresponding column is a boolean column so they convert the string to the appropriate boolean (see https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/column.rb for some of the typecasting )

You could either choose to do the same (ie provide your own setter method that does this conversion) or choose to mangle the parameters in the controller. I find both options a little icky - the model is the one that knows which attribute should be of each type but it feels a little dirty that a detail of the way in which http form posts are handled (values are always strings) ends up in your model.

Fred.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/6d761ef7-026f-4932-a36c-5a22e0f60582%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment