使用selectbox nested_form gem编辑模型

时间:2013-10-08 07:51:30

标签: ruby-on-rails nested-forms nested-attributes

我有一个嵌套的表单宝石问题,几天都无法解决。

当“编辑”模型时,为什么我的选择框没有从数据库中填充当前值?

我的“自定义”视图:

<%= 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%>

我的部分视图(嵌套):

<%= 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 = [
  ["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"]
] 

对于textfield,它可以正常工作(填充当前数据),但如果我使用selectbox则不会

我的控制器中

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

你能告诉我怎么办才能解决这个问题? 真的很感激,谢谢

1 个答案:

答案 0 :(得分:0)

我现在无法测试,但我会这样做:

您的观点 已编辑

<%= 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%>

我们必须将order_custom对象传递给部分

部分

<%= 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" %>

这一行

PRESSED_POSITION.index{|element| element.last==order_custom.pressed_position)

将返回PRESSED_POSITION数组的索引,其中最后一个元素等于对象pressed_position的{​​{1}}属性。

我希望它有所帮助:)