0

我正在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. 我的 .each 块是否适合关联?

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

4

1 回答 1

1

似乎 Ryan Bate 的nested_form是要走的路,它也支持 simple_form

基本用法:

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

然后你希望你的“添加新成分”链接出现在哪里:

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

gem 本身有很好的文档,还可以查看 Wiki 页面。

于 2013-03-01T05:37:43.133 回答