acp-1987
acp-1987

Reputation: 45

How to use include? in Rails

hopefully a trivial question for the masters at SO. How would I use ruby's include? to see if Post's Comment owner includes the current_user? For example, this code works fine, but I'm trying to find the include? method equivalent to test if the User is included. Many thanks in advance!

# Brief has many Submissions
brief = Brief.first
user = User.first
brief.submissions.where('submissions.user': user) # works as expected and retrieves the correct Submission
brief.submissions.include?(user: user) # false but should return true

Upvotes: 0

Views: 152

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

The result of where is an ActiveRecord_Relation, where every element inside is an instance of the same class the receiver is defined as, meaning every element in brief.submissions.where('submissions.user': user) is a Submission instance

In order for include? to return true, you must pass an object that's an instance of Submission, what you're passing right now is a Hash.

To solve that, try instead brief.submissions.include?(user).

But, if your query does what it means to, then you're not getting users as results, but submissions, filtering by the user to which they belong to. So, in any case, no matter what user you pass, it's going to return false.

I recommend you to use exists? if you're expecting to receive just a predicate value:

brief.submissions.exists?('submissions.user': user)

Upvotes: 2

Related Questions