Ok so I’m doing an inner join on an association in rails like so:
@visits = @customer.visits.joins(:messages).select("distinct(visits.id)")
And this is returning unique visit id’s however I want to loop through these visits, and access its associations (Each visit has a merchant_id attached to it as well). The problem with this inner join is that is is only returning the id so when I do something like this:
@visits.each do |v|
merchant = v.merchant
end
I just end up with a nil class.
How can I select “visits” based on a unique visit.id but also return all the other columns in that row? Group by?
All you are selecting is the id, that’s correct. Since you want an object, you have two options. So what you really want is along the lines of:
This is equivalent to:
I’m not sure where ‘messages’ factors in in your schema, but it’s basically just a join in the above query. Sometimes it;s helpful to figure out the SQL, and work backwards to ActiveRecord syntax if you’re having trouble.