2013-02-27 85 views
0

我正在Rails中构建食物食谱的数据库,并且我正尝试构建一个方便的表单来使用Jquery添加配料。Rails/jquery最佳实践

我协会:

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 

我的食谱形式看起来像这样(简化):

<%= 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 %> 

两个问题:

  1. 难道我的。每块寻找正确的联想?

  2. 什么是最好的方式添加到该表客户端的新行,以便表单助手识别新行并创建适当的数据库插入?我不太清楚Rails的魔法如何在创建这样的对象数组方面发挥作用。

+0

您是否想在创建配方时创建配料或将现有配料添加到配方中? – 2013-02-27 18:19:38

+1

@SybariteManoj你是对的,它有很大的不同。至于问题#2,只是一个提示:[嵌套属性](http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html) – 2013-02-27 19:25:48

+0

@m_x是的,如果他想添加新的成分,那么nested_attributes是要走的路,但在这种情况下,不需要“多”关联,因为成分总是会被创造出来。但是如果他想添加现有成分,那么可以使用'ingredient_ids'。在最后一种情况下,当他想要这两种方法时,他可能需要使用先前方法的组合。 :) – 2013-02-27 19:40:40

回答

1

好像瑞安贝特的nested_form是要走的路,它有simple_form也

基本用法支持:

<%= simple_nested_form_for @recipe do |f| %>

那么您希望您的“添加新的成分”链接出现:

<%= f.link_to_add "Add new ingredient", :recipe_ingredients %>

宝石本身有很好的文档,也检查维基页面。