0

我有一个嵌套形式的 gem 问题,好几天都想不通。

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

我的“自定义”视图:

<%= 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 为 CONSTANT 并且数据存储“字符串”值

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"]
] 

对于文本字段它可以工作(填充当前数据),但如果我使用选择框它不会

在我的控制器中:

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

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

4

1 回答 1

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对象的属性order_custom

我希望它有帮助:)

于 2013-10-08T11:42:13.243 回答