开发者

Rails: select helper value after a failed create

I have a nested form, like:

<% form_for @invoice do |f| %>
 <%= render :partial => "invoice_item_fields", :locals => {:f => f} %>
<% end %>

and _invoice_items_fields:

<% f.fields_for :invoice_items do |builder| %>
 <%= link_to_remove_fields "remove", builder %>
 <%= builder.collection_select(:product_id, Product.all, :id, :name) %>
 <%= builder.text_field :quantity, :size => 4,%>
<% end %>

When i submit the form and it not pass the validations it render the new action again. The thing is the selected value for :product_id is no remembered, but the :quantity is ok. I read that i should setup an instance variable in the controller with the value of the selected option and then d开发者_如何学编程o something like:

<%= builder.collection_select(:product_id, Product.all, :id, :name,
:selected => @selected_product) %>

but the thing is the application could have many :invoice_items, so i don't know what to do for the select field "remember" the values.

Thanks.


This sort of issue is often related to the product's id being an integer, but the product_id that the form builder is comparing to being a string. If that's the problem, a fix from the not-beautiful-but-it-works department is to call to_i:

builder.collection_select(builder.object.product_id.to_i, Product.all, :id, :name)

I'd love to see a nicer way of doing that.

The other thing that's often troublesome when debugging selects is that if you refresh the page, firefox leaves a select on the highlighted entry - it doesn't consult the HTML again and select what it now says should be selected. This means that if you initially have the wrong selected attribute, then correct the code and hit refresh, your browser won't actually show you the change.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜