带有has_many:through和link_to_add_hmt函数的nested_form

时间:2015-09-16 01:55:25

标签: ruby-on-rails ruby nested-forms has-many-through

我遇到与this question相同的问题。解决方法是使用我已添加到 nested_form 的源代码中的link_to_add_hmt函数,但我&# 39;我有一些问题。我不确定我做错了什么,或者是否有人熟悉修改过这个版本的功能(只有真正的区别似乎是第6和第36行)。我有3个型号:

class Recipe < ActiveRecord::Base
    has_many :recipe_ingredients, :dependent => :destroy
    has_many :ingredients, through: :recipe_ingredients
    accepts_nested_attributes_for :recipe_ingredients,
                                  :reject_if => :all_blank,
                                  :allow_destroy => true
    accepts_nested_attributes_for :ingredients
...

class RecipeIngredient < ActiveRecord::Base
    belongs_to :recipe
    belongs_to :ingredient
...

class Ingredient < ActiveRecord::Base
    has_many :recipe_ingredients
    has_many :recipes, through: :recipe_ingredients

    accepts_nested_attributes_for :recipes
    accepts_nested_attributes_for :recipe_ingredients
...

这是我的形式部分:

<%= bootstrap_nested_form_for @recipe, :html => { :multipart => true } do |f| %>
...
    <%= f.text_field :name, label: "Recipe Name" %>
    <%= f.text_area :description, label: "Description" %>
    <%= f.file_field :image, label: "Image" %>
    <table id="ingredients">
        <%= f.fields_for :recipe_ingredients, :wrapper => false do |ingredient_form| %>
        <tr class="fields">
        <%= ingredient_form.fields_for :ingredient do |ingredient| %>
            <td><%= ingredient.text_field :name, label: "ingredient" %></td>
        <% end %>
            <td><%= ingredient_form.link_to_remove "Remove" %></td>

        </tr>
        <% end %>
    </table>
    <p><%= f.link_to_add_hmt "Add ingredient", :ingredients, recipe_ingredients, :data => { :target => "#ingredients" } %></p>
    <br />
    <%= f.text_area :directions, label: "Directions" %>
    <%= f.submit %>
<% end %>

我收到错误:

undefined method `build_ingredients' for
#<RecipeIngredient:0x007f69057592a0>

据我所知,这一点发生在link_to_add_hmt的这一行(上面的链接中有36条):

model_object.send("build_#{association_two}".to_sym)

我不确定我是否使用了错误的功能,我错过了某些内容,或者link_to_add_hmt中的代码是否由于某种原因无效。

此外,我在Ruby 2.1.0上运行Rails 4.2.4,如果这与此错误完全相关。

2 个答案:

答案 0 :(得分:0)

您是否在帮助程序中定义了link_to_add_hmt方法?如果您正在使用该解决方案。

答案 1 :(得分:0)

在将此行添加到问题排查后,我想出来了:

raise "debug: association => #{association}, association_two => #{association_two}, model_object => #{model_object.methods}"

我发现我有一个错字。由 belongs_to 关系生成的 build_other 方法是单数的(在本例中为 recipe_ingredients.build_ingredient )。我输入了:ingredients (复数)。