【问题标题】:Rails / Jquery best practiceRails / Jquery 最佳实践
【发布时间】:2013-02-27 17:26:46
【问题描述】:

我正在 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 魔术在创建这样的对象数组方面是如何工作的。

【问题讨论】:

  • 您想在创建食谱时创建配料还是将现有配料添加到食谱中?
  • @SybariteManoj 你是对的,它有很大的不同。至于问题#2,只是一个提示:nested attributes
  • @m_x 是的,如果他想添加新成分,那么可以使用 nested_attributes,但在这种情况下,不需要 many-many 关联,因为总是会创建成分。但是如果他想添加现有的成分,那么可以使用ingredient_ids。在最后一种情况下,当他想要两者时,他可能需要结合使用以前的方法。 :)
  • 我不想创建新成分,但我确实想使用 recipe_ingredients 连接表将现有成分分配给配方。我没有提到我的 Recipe 模型有一个 accept_nested_attributes_for 调用。将其添加到我原来的问题中。
  • 我应该补充一点,我非常了解关联是如何工作的,而且我大约 99% 确信我已经正确设置了这些。我还没有掌握的是如何设置一个表格来反映这些关联。通常我会在表单字段名称中创建一个数组并在控制器中执行对象构建逻辑,但如果我正确设置表单字段,Rails 可能已经涵盖了这一点。

标签: ruby-on-rails forms associations


【解决方案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 页面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2011-03-14
    相关资源
    最近更新 更多