【发布时间】:2015-07-26 14:57:12
【问题描述】:
我有三个模型 PriceGroup、PriceGroupLine 和 Item。
PriceGroup has fields - :id and :name.
Item has fields - :id and :name.
PriceGroupLine has fields - :id, :price_group_id, :item_id, :price
协会:
PriceGroup has_many PriceGroupLines
Item has_one PriceGroupLine
PriceGroupLine belongs_to Item
PriceGroupLine belongs_to PriceGroup
我需要从 PriceGroup 显示视图中插入 PriceGroupLine 模型线。如果我需要在 PriceGroupLine 中插入,我应该如何组织 form_for 助手:
item_id - items list organized with collection_select helper
price_group_id
price of item
我正在查看此代码,但我无法插入它:
<%= form_for @price_group, html: {class: "form-inline"} do |f| %>
<div class="form-group">
<label>Товар</label>
<%= f.collection_select(:id, Item.all, :id, :name, {}, {class: "form-control"}) %>
</div>
<div class="form-group">
<label>Цена</label>
<%= f.text_field :price, class: "form-control" %>
</div>
<%= f.submit "Добавить", class: "btn btn-default" %>
<% end %>
还有一个关于关联的问题。一开始我有这样的联想:
PriceGroup has_many PriceGroupLines
PriceGroupLine has_many Items
Item belongs_to PriceGroupLine
PriceGroupLine belongs_to PriceGroup
但是当我尝试从 Item 模型中获取 :name 字段时,这种关联无法正常工作:
<% @price_group.price_group_lines.each do |price_group_line| %>
<%= price_group_line.item.try(:name) %>>
<%= price_group_line.price %>
<% end %>
我改变了关联并且一切正常。现在PriceGroupLine belongs_to :item 和Item has_one :price_group_line。但假设ITEM 属于PriceGroupLine(PRICEGROUPLINE 包含ITEM)是合乎逻辑的。我错了吗?
更新 快到了:)) 这是我的表单的屏幕截图。
显示视图PriceGroup的代码:
<%= form_for @price_group, html: {class: "form-inline"} do |f| %>
<%= f.fields_for :price_group_lines do |price_group_line| %>
<%= render partial: "price_group_line_fields", locals: { f: price_group_line } %>
<% end %>
.links
<%= link_to_add_association "Добавить", f, :price_group_lines %>
<% end %>
部分代码:
<div class="form-group">
<label>Товар</label>
<%= f.collection_select(:item_id, Item.all, :id, :name, {}, {class: "form-control"}) %>
</div>
<div class="form-group">
<label>Цена</label>
<%= f.text_field :price, class: "form-control" %>
</div>
在页脚帮助器为数据库中的每条记录创建字段。我只需要项目列表来选择合适的项目和空白字段 PRICE 来输入价格。并且出现了一些 .link 字样。
【问题讨论】:
-
实际上之前你有
PriceGroupLine has_many Items,所以因为price_group_line.item.name没有工作,因为price_group_line没有一个项目,它有多个。现在关于新的关联,如果它们满足您的需求,它们似乎是正确的。但是,如果您遇到任何问题或错误,仍然在视图上使用它们,然后请发布它,以便我们可以帮助您解决该错误。 -
此表单不起作用,我不知道如何修复它。
<%= form_for @price_group, html: {class: "form-inline"} do |f| %> <div class="form-group"> <label>Item</label> <%= f.collection_select(:id, Item.all, :id, :name, {}, {class: "form-control"}) %> </div> <div class="form-group"> <label>Price</label> <%= f.text_field :price, class: "form-control" %> </div> <%= f.submit "Add Item", class: "btn btn-default" %> <% end %> -
对于
links这个词我已经更新了这个问题。由于它是字段的形式,它也显示现有字段以供编辑。 -
如何让表单添加新值而不显示现有字段?这个代码
<%= link_to_add_association "Добавить", f, :price_group_lines %>给了我一个链接http://localhost:3000/price_groups/5# -
你是否使用了
cocoongem 并包含了它的js?
标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4