winston
winston

Reputation: 3100

Rails query not equal

My rails app has 3 components: -users (has many works and comments) -works (blog posts) (belongs to users, has many comments) -comments (comments belong to both users and work)

I'm trying to display all the comments on a page for a particular user except comments made on blog posts that belong to him/her. What should my query look like in the controller?

Here is what I have so far. It does not load any comments at all.

    @user = User.find(params[:id])
    @works = Work.pluck(:user_id)
    @comments = @user.comments.where(is_boolean_value: true).where(['user_id NOT IN(?)', @works]).all

How can I change this query so that shows all comments made by a user where the user did not own the work?

Thanks! -b

Upvotes: 1

Views: 172

Answers (1)

Aditya Nagrath
Aditya Nagrath

Reputation: 421

The first problem is the

Work.pluck(:user_id)

That fetches the user_id for any user that has an object of table Work. Instead, fetch the work ids for the items the user created:

@works = @user.works.map {|obj| obj.id}

Then ask the database to give you all the comments that belong to that user but do not belong to one of his works:

@comments = @user.comments.where('work_id NOT IN(?)', @works)

Upvotes: 3

Related Questions