Active Record Association Product belongs_to User
I am trying to associate a user with their created products but I am having issues with it. My models look like the following.
class Product < ActiveRecord::Base
belongs_to :category
b开发者_如何学Celongs_to :user
def userid
@user_id = @product.user
end
end
class User < ActiveRecord::Base
has_many :products, :foreign_key => 'user_id'
end
I'm getting a nil object
with the following view <%= @product.userid %>
- You don't need the
Product#userid
method at all. - In the
Product#userid
method you reference@product
. That's aproduct
instance variable on Product. You don't need an instance variable to refer to an object from itself, you simply useself
, but it's implicit most of the time. You only actually need it in ambiguous cases (likeuser_id = 1
which could either beself.user_id=(1)
OR assigning a localuser_id
variable to1
). - You don't need to specify the
foreign_key
on yourUser
model because you're following convention.
So the following should work for you just fine:
class Product < ActiveRecord::Base
belongs_to :category
belongs_to :user
end
class User < ActiveRecord::Base
has_many :products
end
@product = Product.first
@product.user #=> <User :foo => 'bar'>
@user = User.first
@user.products.create :some_attribute => 'some value'
精彩评论