我正在跟踪一个railscast,试图创建一个添加链接来添加一个与多对多关联相关的值。我使用模型而不是
实现了多对多的唯一区别has_and_belongs_to_many.
它并没有那么好用。
(presenetation很好,但添加按钮失败。)
这是我的代码
档案:ingredient_recipe.rb
class IngredientRecipe < ActiveRecord::Base
attr_accessible :created_at, :ingredient_id, :order, :recipe_id
belongs_to :recipe
belongs_to :ingredient
end
文件:ingredient.rb
class Ingredient < ActiveRecord::Base
has_many :ingredient_recipes
has_many :recipes, :through => :ingredient_recipes
...
文件:recipes.rb
class Recipe < ActiveRecord::Base
has_many :ingredient_recipes
has_many :ingredients, :through => :ingredient_recipes
...
<%= link_to_add_fields "Add", f, :ingredient_recipes %>
定义方法
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
end
问题
的
渲染(association.to_s.singularize +“_ fields”,:f =&gt; builder)
显示器
&lt;%= f.text_field:name%&gt;
&lt;%= f.hidden_field:_destroy%&gt;
&lt;%= link_to“x”,“”,类:“remove_fields”%&gt;
并打印错误
ActionView::Template::Error (undefined method `name' for #<IngredientRecipe:0x6393ee8>):
任何想法?
答案 0 :(得分:1)
不完全确定是不是这样,但由于它试图在ingredient_recipe对象上调用name,您是否尝试更改方法中传递的符号?
<%= link_to_add_fields "Add", f, :ingredients %>