【发布时间】:2015-08-19 12:20:37
【问题描述】:
这是我的问题的后续:Rails 4 - Access Join Table Value in views
现在我知道如何检索连接表属性并将它们显示在视图中。但我仍然找不到编辑和更新属性的正确方法。
型号:
class Recipe < ActiveRecord::Base
has_many :recipe_ingredients
has_many :ingredients, through: :recipe_ingredients
end
class Ingredient < ActiveRecord::Base
has_many :recipe_ingredients
has_many :recipes, through: :recipe_ingredients
end
class RecipeIngredient < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
#there is an attribute t.text :amount
end
配方#编辑:
...
<%= simple_form_for @recipe do |f| %>
<div class="form-group">
<%= f.input :name, input_html: { class: "form-control"} %>
<%= f.input :description, input_html: { class: "form-control"} %>
<%= f.collection_select(:ingredient_ids, Ingredient.all, :id, :title, {}, {multiple: true}) %>
<!-- reserve for recipe_ingredients.amount -->
</div>
<%= f.submit "Submit", disable_with: 'Submitting...', class: "btn btn-primary"%>
<% end %>
...
如上所示,这是一个多对多的关系,每个食谱可能有几种成分。它工作正常,我可以选择正确的模型来关联(使用collection_select)。但是我没有完成编辑和更新连接表属性的工作。我脑子里有两个想法:
- 制作另一个编辑页面以编辑连接模型属性
- 阿贾克斯?但不太熟悉
我知道这个问题似乎微不足道,但许多解决方案已经过时(Rails 3)。迫切需要 Rails 4 解决方案。
编辑
意图:我想自己创建配方和成分模型,已经完成。用户将看到使用成分#show 操作中的成分的配方,这也是完成的。至于 Recipe#show 动作,有一点不同,用户将看到它使用的成分以及数量(连接表属性),这在我之前的问题中完成。最后一个问题是,我想让这个属性可编辑。
【问题讨论】:
-
一种解决方案是将其设为“手动”,为每个配方添加一个输入字段,然后在您的控制器中读取并设置该值。我想有一个
simple_form and rails- 解决方案,但我很想阅读它。 -
有参考资料吗?
标签: ruby-on-rails-4 has-many-through jointable