Ruby on rails Rails/Jquery最佳实践
我正在Rails中构建一个食品配方数据库,并尝试使用Jquery构建一个方便的表单来添加配料 我的协会:Ruby on rails Rails/Jquery最佳实践,ruby-on-rails,forms,associations,Ruby On Rails,Forms,Associations,我正在Rails中构建一个食品配方数据库,并尝试使用Jquery构建一个方便的表单来添加配料 我的协会: class Recipe < ActiveRecord::Base has_many :recipe_ingredients has_many :ingredients, :through => :recipe_ingredients accepts_nested_attributes_for :recipe_ingredients end class Ingre
class Recipe < ActiveRecord::Base
has_many :recipe_ingredients
has_many :ingredients, :through => :recipe_ingredients
accepts_nested_attributes_for :recipe_ingredients
end
class Ingredient < ActiveRecord::Base
end
class RecipeIngredient < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
end
类配方:recipe\u配料
接受以下内容的\u嵌套\u属性\u:recipe\u配料
结束
类组件
我的配方表如下所示(简化):
成分
两个问题:
然后,您希望“添加新成分”链接出现在何处:
gem本身有很好的文档,也可以查看Wiki页面。您想在创建配方时创建配料,还是将现有配料添加到配方中?@SybariteManoj您是对的,这会带来很大的不同。至于问题#2,只是一个提示:@m#x是的,如果他想添加新的成分,那么嵌套的#u属性是可行的,但在这种情况下,不需要进行
many-many
关联,因为成分总是会被创建的。但如果他想添加现有成分,则可以使用成分ID
。在最后一种情况下,如果他想要两者兼而有之,那么他可能需要结合使用前面的方法我不想创建新的配料,但我想使用recipe_配料联接表将现有配料分配给配方。我忽略了提到我的配方模型有一个accepts\u嵌套的\u attributes\u调用。在我最初的问题中补充了这一点。我应该补充一点,我非常了解关联是如何工作的,我大约99%确信我已经正确地设置了这些关联。我还没有掌握的是如何建立一个表格来反映这些关联。通常,我会在表单字段名中创建一个数组,并在控制器中执行对象构建逻辑,但如果我正确设置表单字段,Rails可能已经涵盖了这一点。
<%= simple_form_form(@recipe) do |f| %>
<div class="form-inputs">
<%= f.input :name %>
<fieldset><legend>Ingredients</legend>
<table class="table">
<% @recipe.recipe_ingredients.each do |recipe_ingredient| %>
<tr>
<%= f.fields_for :recipe_ingredients, recipe_ingredient do |dif| %>
<td><%= dif.text_field :ingredient %></td>
<td><%= dif.text_field :amount %></td>
<% end %>
</tr>
<% end %>
</table>
<div class="btn-group">
<a href="#" class="btn btn-primary">Add New Ingredient</a>
</div>
</fieldset>
</div>
<% end %>