legendary_rob
legendary_rob

Reputation: 13012

Ruby find User with specific Post contents

Class User 
  has_many :posts
end

Class Post
  belongs_to :users
end

I have a post's content and would like to find out if a user ever sent a post with the same content. I could find it out easily if I was only searching against a single user.

user.posts.exists?(content: params[:content])

I would like to look through all the users in the DB.

users = Users.all
users.posts # will not work NoMethodError: undefined method `posts' for #<Array:0x007fbe818fbd98>

I need either a true as soon as there is a single match or a false if there is no user with matching content, for all the posts posted from all the users.

I could always loop this in a block and get a result this way, is there a way of doing this in a single line of code?

Upvotes: 1

Views: 63

Answers (1)

Dmitry Sokurenko
Dmitry Sokurenko

Reputation: 6132

Try something like this:

posts = Post.where(content: params[:content])
users = User.find posts.map(&:user_id)

Or a shorter one:

users = User.find Post.where(content: params[:content]).pluck(:id)

Or if you just need to check whether a post (created by any user) with a given content exist:

Post.exists?(content: params[:content])

Upvotes: 3

Related Questions