whalelee
whalelee

Reputation: 21

Inner join in ruby on rails 4

I encountered "undefined method 'join'" error when I try to display all the clubnames that the current user requested.

In my controller:

@clubs = Club.find(:conditions=> ["Request.userid = session[:userid]"],
                                     :joins=>[:Request])

In my view:

@clubs.each do |c| 
  c.clubname
end 
The equivalent query that I wish to load is

SELECT clubname FROM clubs 
INNER JOIN request 
ON request.clubid = clubs.clubid 
WHERE request.userid = session[:userid]

Been modifying my code from various sources but doesnt seem working... The sources that I have been trying out are: railsforum and dsone but they don't seem to work in my code.

Upvotes: 1

Views: 582

Answers (2)

Joe Kennedy
Joe Kennedy

Reputation: 9443

One way to get what you're looking for would be:

@clubs.joins(:request).where(request: { userid: session[:userid] })

UPDATE: The doesn't seem to be working for the OP, most likely because as @vee pointed out, the table is singular. If that's the case, it'll need to be a bit less pretty:

@clubs.joins('request').where('request.user_id = ?', session[:userid])

Upvotes: 2

vee
vee

Reputation: 38645

Your use of conditions suggests that Request is a database table in mysql. That table name is usually and according to Rails, pluralized and lowercased. Try:

@clubs = Club.find(:conditions=> ["requests.userid = ?", session[:userid]], :joins=>[:Request]) 

I'm unsure why your :Request is capitalized in joins, that also I believe by convention is supposed to be :request.

The second problem is the use of "requests.userid = session[:userid]". Note that the session[:userid] is not going to be interpolated here. As suggested you should be using parameterized query as updated in the code snippet above.

And you already have another answer by @JKen13579 here which looks much better syntactically!

Upvotes: 1

Related Questions