Lut
Lut

Reputation: 1533

Rails Custom foreign_key gives NoMethodError

I have the following Models:

User

class User < ActiveRecord::Base
  ...
  attr_accessible :email

  has_many :ingredients, class_name: "Ingredient", foreign_key: "created_by"
end

Ingredient

class Ingredient < ActiveRecord::Base
 ...
 attr_accessible :created_by
  belongs_to :user
end

I created one ingredient and it has the created_by field populated. If I do:

> u = User.find(1)
> u.ingredients.size
=> 1

So the relationship is working! But if I do:

Ingrendient.last.created_by.email

I get the following error:

1.9.3-p362 :012 > Ingredient.last.created_by.email
Ingredient Load (0.3ms)  SELECT "ingredients".* FROM "ingredients" ORDER BY "ingredients"."id" DESC    LIMIT 1
NoMethodError: undefined method `email' for 1:Fixnum
from (irb):12
from /Users/andreucasadella/.rvm/gems/ruby-1.9.3-p362/gems/railties-3.2.11/lib/rails/commands/console.rb:47:in `start'
from /Users/andreucasadella/.rvm/gems/ruby-1.9.3-p362/gems/railties-3.2.11/lib/rails/commands/console.rb:8:in `start'
from /Users/andreucasadella/.rvm/gems/ruby-1.9.3-p362/gems/railties-3.2.11/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

Why?

Upvotes: 1

Views: 102

Answers (1)

blelump
blelump

Reputation: 3243

It should be:

class Ingredient < ActiveRecord::Base
 # ...
 belongs_to :user, foreign_key: :created_by
end

class User < ActiveRecord::Base

  has_many :ingredients, foreign_key: :created_by
end

Also, remove created_by from users table and add to ingredients. I assume you want to associate Ingredient with User which is reasonable, so that Ingredient needs created_by foreign key.

Note that, I've dropped attr_accessible. For Rails 4.0+ strong parameters are used (unless you're using Rails < 4) .

Upvotes: 1

Related Questions