form_for与其他模型的ckeckbox_tag

时间:2012-12-10 00:58:46

标签: ruby-on-rails

我是rails的新手,只是无法解决问题。

我有3个型号。订单,产品和LineItems。 我想要一个带有每个产品复选框的订单。用户选择适当的产品并提交订单。

我无法获取表单来创建正确的哈希值。

class Order < ActiveRecord::Base
  attr_accessible :account_id, :user_id

  has_many :line_items, :dependent => :destroy
end

class LineItem < ActiveRecord::Base
  attr_accessible :account_id, :product_id, :order_id

  belongs_to :orders
  belongs_to :product
end

这里的观点:

<%= form_for 'line_items[]' do |f|  %>
   <%= f.select :account_id, options_from_collection_for_select( Account.all, 
       :id, :name ), :prompt => 'Select Account' %>

<% Product.all.each do |product| %>
<div>
       <%= check_box_tag 'line_items[product_ids][]', product.id %>
</div>
<% end -%>

    <div>       
    <%= f.submit 'save' %>
</div>

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要在模型中使用accepts_nested_attributes_for来启用关联模型的嵌套属性。您可能还想查看此railscast并根据您的需求进行调整。

例如在订单模型中:

class Order < ActiveRecord::Base
  attr_accessible :account_id, :user_id

  has_many :products #This makes the association to products
  has_many :line_items, :dependent => :destroy

  accepts_nested_attributes_for :products #This allows the attributes from products accessible
end

然后表格可能是:

<%= form_for @order do |f| %>

  <%= f.select :account_id, options_from_collection_for_select( Account.all, 
       :id, :name ), :prompt => 'Select Account' %>

  <%= f.fields_for :product do |product_form| %>
    <%= product_form.check_box :id  %>
  <% end %>

  <%= f.submit %>
<% end %>