Yshmarov
Yshmarov

Reputation: 3749

current_user can see comments only to his posts

What I have:

scaffold Post title body user_id
scaffold Comment body tag post:references
post has_many :comments

Current comments controller:

  def index
    @comments = Comment.where(tag: [1, 3])
  end

I want to enable current devise user to see a list of comments to all only his posts. How can it be done? Something with current_user?

Upvotes: 2

Views: 532

Answers (3)

TJR
TJR

Reputation: 311

If you wish to base a query off of information in the column of an associated model, you should use either a .joins or a .include call. Based on the setup you have indicated, this ought to be what you need:

@comments = Comment.joins(:post).where("posts.user_id": current_user.id)

Or simply:

@comments = Comment.joins(:post).where("posts.user_id": current_user)

It may be worth breaking this off into a scope on the Comment model if you intend to call it elsewhere.

class Comment < ActiveRecord::Base
  belongs_to :post
  scope :on_user_posts, ->(user) { joins(:post).where("posts.user_id": user) }

then you can call this in the controller:

@comments = Comment.on_user_posts(current_user)

You can also chain this scope with the conditions you already have, if needed:

@comments = Comment.on_user_posts(current_user).where(tag: [1, 3])

Upvotes: 2

Bart Jedrocha
Bart Jedrocha

Reputation: 11570

You can setup a has_many :through relationship directly on the User model assuming you already have a has_many :posts relationship defined and the appropriate relationship on Post and Comment. For example,

class User < ActiveRecord::Base
  has_many :posts
  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

Now, since devise gives you current_user, getting a user's comments is straightforward

def index
  @comments = current_user.comments
end

def show
  @comment = current_user.comments.find(params[:id])
end

Hope this helps. Cheers.

Upvotes: 4

MayankJ
MayankJ

Reputation: 446

Define associations and scope in the model

class Comment < ActiveRecord::Base
    belongs_to :post
    scope :on_user_posts, lamda{ |user| joins(:post).where("posts.user_id = ?", user.id) }

And you post model

class Post < ActiveRecord::Base
  has_many :comments

Now call this scope

@comments = Comment.on_user_posts(current_user).where(tag: [1, 3])

Upvotes: 2

Related Questions