开发者

rails check_box failing on boolean attribute

I have a postgres db with a bool field :on_farm_tour. But I'm getting this in the view:

undefined method `to_i' for #<Class:0x10ddec5c0>
Extracted source (around line #10):

7: 
8: %p
9:   =f.label :on_farm_tour, "This farm is in the Farm开发者_如何学JAVA Tour?"
10:   =f.check_box :on_farm_tour
11: 
12: %p
13:   =f.label :last_mile_directions, 'Enter driving directions from the last point displayed by Google Maps for this farm to the actual location of the farm'

Obviously I know that true.to_i is undefined, but what is the proper way to handle this?


It seems to be a gotcha issue. Try to use check_box_tag instead. Take a look at what apidock.com says about it:

Gotcha

The HTML specification says unchecked check boxes are not successful, and thus web browsers do not send them. Unfortunately this introduces a gotcha: if an Invoice model has a paid flag, and in the form that edits a paid invoice the user unchecks its check box, no paid parameter is sent. So, any mass-assignment idiom like

@invoice.update_attributes(params[:invoice])

wouldn’t update the flag.

To prevent this the helper generates an auxiliary hidden field before the very check box. The hidden field has the same name and its attributes mimic an unchecked check box.

This way, the client either sends only the hidden field (representing the check box is unchecked), or both fields. Since the HTML specification says key/value pairs have to be sent in the same order they appear in the form, and parameters extraction gets the last occurrence of any repeated key in the query string, that works for ordinary forms.

Unfortunately that workaround does not work when the check box goes within an array-like parameter, as in

<%= fields_for "project[invoice_attributes][]",

invoice, :index => nil do |form| %> <%= form.check_box :paid %> ... <% end %>

because parameter name repetition is precisely what Rails seeks to distinguish the elements of the array. For each item with a checked check box you get an extra ghost item with only that attribute, assigned to "0".

In that case it is preferable to either use check_box_tag or to use hashes instead of arrays.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜