Akhil
Akhil

Reputation: 103

How to find out user name

I have this setup:

class User < ActiveRecord::Base
  has_many :posts, :dependent => :destroy  
  has_many :comments, :through => :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

How I can fetch the user name that make a comments?

Upvotes: 0

Views: 79

Answers (2)

Anezio Campos
Anezio Campos

Reputation: 1555

You can use delegate

class Comment < ActiveRecord::Base
  belongs_to :post

  delegate :user, to :post
end

Then in your code you can access

@comment.user

Upvotes: 0

DMKE
DMKE

Reputation: 4603

You are missing the Comment-belongs-to-User association:

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

This way you can fetch the commentor quite easily:

@comment.user

Upvotes: 1

Related Questions