Jonathan Clark
Jonathan Clark

Reputation: 20538

Cannot get data from both tables in a join query using Rails 3

I am using Rail 3 and I am finding it very hard to do a join of two tables AND get access to data from both of them in the view. I only get access to one of the two. What is wrong with the below code? How should it look like?

Please note that I am using Rails 3.

@contacts = Profile.where("profiles.id = ?", @profile).includes(:contacts).order("lastname ASC")

I have also tried something like this

@contacts = Profile.joins('LEFT OUTER JOIN contacts ON contacts.friend_id = profiles.id').where("profiles.firstname LIKE :input OR profiles.lastname LIKE :input",{:input => "#{params[:keyword]}%"}).where("contacts.profile_id = #{params[:profile_id]}")

Upvotes: 1

Views: 1605

Answers (1)

Leonel Galán
Leonel Galán

Reputation: 7167

You are missing the select method

See this question solution: Rails 3 - select with Include? It works similar with a JOIN, allowing you to select fields from both tables but the results will be in a Profile object with Contact fields as virtual columns.

Upvotes: 2

Related Questions