1

我是 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>

谢谢!

4

1 回答 1

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 %>
于 2012-12-10T06:25:43.703 回答