0
votes

I was following a railscast trying to create a add link to add a value connected with many to many associtation. the only difference that I have implemented the many to many using a model and not

has_and_belongs_to_many. 

and it doesnt work so well .
(The presenetation is fine but the add button fails. )

here is my code

File:ingredient_recipe.rb

class IngredientRecipe < ActiveRecord::Base
  attr_accessible :created_at, :ingredient_id, :order, :recipe_id
  belongs_to :recipe
  belongs_to :ingredient
end

File:ingredient.rb

class Ingredient < ActiveRecord::Base
 has_many :ingredient_recipes
 has_many :recipes, :through => :ingredient_recipes
 ...

File:recipes.rb

class Recipe < ActiveRecord::Base
 has_many :ingredient_recipes
 has_many :ingredients, :through => :ingredient_recipes
 ...

in the ui

 <%= link_to_add_fields "Add", f, :ingredient_recipes %>

the method is defined

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

The Problem

the
render(association.to_s.singularize + "_fields", :f => builder) displays
<%= f.text_field :name%> <%= f.hidden_field :_destroy%> <%= link_to "x","", class: "remove_fields"%> and prints an error

 ActionView::Template::Error (undefined method `name' for #<IngredientRecipe:0x6393ee8>):

any ideas?

1

1 Answers

1
votes

Not entirely sure if this is it, but since it's trying to call name on the ingredient_recipe object, have you tried changing the symbol passed in the method?

 <%= link_to_add_fields "Add", f, :ingredients %>