开发者

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 %>


  1. You don't need the Product#userid method at all.
  2. In the Product#userid method you reference @product. That's a product instance variable on Product. You don't need an instance variable to refer to an object from itself, you simply use self, but it's implicit most of the time. You only actually need it in ambiguous cases (like user_id = 1 which could either be self.user_id=(1) OR assigning a local user_id variable to 1).
  3. You don't need to specify the foreign_key on your User 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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜