我有以下型号:
用户
class User < ActiveRecord::Base
...
attr_accessible :email
has_many :ingredients, class_name: "Ingredient", foreign_key: "created_by"
end
成分</ P>
class Ingredient < ActiveRecord::Base
...
attr_accessible :created_by
belongs_to :user
end
我创建了一个成分,并且填充了created_by字段。如果我这样做:
> u = User.find(1)
> u.ingredients.size
=> 1
所以关系正在发挥作用!但如果我这样做:
Ingrendient.last.created_by.email
我收到以下错误:
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>'
为什么?
答案 0 :(得分:1)
应该是:
class Ingredient < ActiveRecord::Base
# ...
belongs_to :user, foreign_key: :created_by
end
class User < ActiveRecord::Base
has_many :ingredients, foreign_key: :created_by
end
另外,从created_by
表中移除users
并添加到ingredients
。我假设您要将Ingredient
与User
相关联,这是合理的,因此Ingredient
需要created_by
个外键。
请注意,我已放弃attr_accessible
。对于Rails 4.0+ strong parameters被使用(除非您使用Rails&lt; 4)。