问题
I have a nested form gem issue and can't figure it out for days.
When "edit" model, why my selectbox not filled with current value from database?
my "customize" view :
<%= nested_form_for @order_detail, :url => create_customize_cart_path do |f| %>
# some field here
<%= f.fields_for :order_customs do |builder| %>
<%= render "order_customs_form", :f => builder %>
<% end %>
<%= f.link_to_add "Add Order Customize", :order_customs %>
<%= f.submit %>
<%end%>
my partial view (as nested) :
<%= f.label :pressed_position, "Position" %>
<%= f.select :pressed_position, options_for_select(PRESSED_POSITION), {:include_blank => '-- Select Position --'} %>
<%= f.link_to_remove "Remove Customize" %>
PRESSED POSITION as CONSTANT and data store "string" value
PRESSED_POSITION = [
["Top", "top"],
["Center","center"],
["Bottom","bottom"],
["Right", "right"],
["Left", "left"],
["Top Left", "top left"],
["Top Center", "top center"],
["Top Right", "top right"],
["Center Left", "center left"],
["Center Center", "center center"],
["Center Right", "center right"],
["Bottom Left", "bottom left"],
["Bottom Center", "bottom center"],
["Bottom Right", "bottom right"]
]
For textfield it works (filled with current data), but if i using selectbox it doesn't
in my controller :
def customize
@order_detail = OrderDetail.find_by_id(decrypting_id(params[:id])) rescue nil
if @order_detail.present?
if (current_user == @order_detail.order.user || temporary_user == @order_detail.order.temp_user_id) && @order_detail.order.order_status_id == 1
1.times{@order_detail.order_customs}
else
# else going here
end
else
# else going here
end
end
Can You guys tell me what should I do to solve this problem? Realy appreciate it, thank you
回答1:
I can't test it right now, but I would do it like this:
your view EDITED
<%= nested_form_for @order_detail, :url => create_customize_cart_path do |f| %>
# some field here
<% @order_detail.order_customs.each do |order_custom| %>
<%= f.fields_for :order_customs, order_custom do |builder| %>
<%= render "order_customs_form", :f => builder, :order_custom => order_custom %>
<% end %>
<% end %>
<%= f.link_to_add "Add Order Customize", :order_customs %>
<%= f.submit %>
<%end%>
We have to pass the order_custom
object to the partial
The partial
<%= f.label :pressed_position, "Position" %>
<%= f.select :pressed_position, options_for_select(PRESSED_POSITION, PRESSED_POSITION.index{|element| element.last==order_custom.pressed_position), {:include_blank => '-- Select Position --'} %>
<%= f.link_to_remove "Remove Customize" %>
This line
PRESSED_POSITION.index{|element| element.last==order_custom.pressed_position)
will return the index of the PRESSED_POSITION
array where the last element is equal to the pressed_position
attribute of the object order_custom
.
I hope it helps :)
来源:https://stackoverflow.com/questions/19242056/edit-model-using-selectbox-nested-form-gem