【发布时间】:2013-11-09 09:47:39
【问题描述】:
我的应用程序有客户和项目。对于不同的客户,商品可以有不同的价格。所以,我有一个 prices 表,它同时引用了 customers 和 items 表。
创建新项目时,我希望用户还能够在同一个表单上为每个客户单独设置每个价格。因此,在该项目表单上,如果有 3 个客户,我应该会看到 3 个名称,每个名称旁边都有一个价格字段。
问题是,这些价格记录还不存在,我不知道如何构建该列表并正确呈现它。
如何构建此表单?
以下是我到目前为止所得到的(尽可能蒸馏)。
[UPDATE] - 我已经弄清楚如何在视图中呈现所有字段。但是,每个生成的价格字段的 ID 最终都是相同的,我认为这会破坏发送的 JSON(即使表单上有多个价格字段,也只会收到一个价格)。根据文档,我认为我应该能够在 fields_for 中包含数组 (@item.prices),而不是 @items.prices.each,但这会引发 price_in_cents 的“未定义方法错误”。
客户模型:
class Customer < ActiveRecord::Base
has_many :prices
has_many :items, through: :prices
end
物品型号:
class Item < ActiveRecord::Base
has_many :prices
has_many :customers, through: :prices
accepts_nested_attributes_for :prices
end
价格模型:
class Price < ActiveRecord::Base
belongs_to :item
belongs_to :customer
end
新项目操作:
def new
@item = Item.new
@customers = Customer.all
@customers.each do |cust|
@item.prices.build
# somehow need to also make all these new items have the correct customer IDs
end
end
当前新项目视图:[已更新]
<%= form_for :item, url: items_path do |f| %>
<p>
<%= f.label :name, 'Item Name' %><br />
<%= f.text_field :name, class: 'form-control', :autofocus => true %>
</p>
<% @item.prices.each do |item| %>
<%= f.fields_for :prices, item do |p| %>
<p>
<%= p.label :price_in_cents, 'Price' %><br />
<%= p.text_field :price_in_cents, class: 'form-control' %>
</p>
<% end %>
<% end %>
<div class="form-group">
<%= f.submit 'Create', class: 'btn btn-primary' %>
</div>
<% end %>
我是 RoR 新手,我很难想象应该如何构建它。有什么见解吗?
【问题讨论】:
-
谢谢,我正在研究这些剧集,但在我的特殊情况下仍然没有点击。我更新了我的问题,希望能澄清我到底需要做什么。
标签: ruby-on-rails ruby-on-rails-4 nested-forms