Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to use "joins" in sql query for a has_one association

I have a User model and a Profile model. Each User has_one profile. The profile has a city attribute. Now, I want the index action of the Users controller to pull all users with the same city as the current_user. So I have this code in the controller:

def index @users = User.same_city_as(current_user).paginate :page => params[:page], :per_page => 10 end

I also have this is in the User model:

scope :same_city_as, lambda { |user| joins(:profile).where(:profile => {:city => user.profile.city} ) }

This does not work. I am getting this error " "PGError: ERROR: missing FROM-clause entry for table "profile" ".

like image 456
pratski Avatar asked Dec 21 '22 08:12

pratski


1 Answers

You need to make :profile in the where clause plural.

 joins(:profile).where(:profiles => {:city => user.profile.city})
like image 131
rocket scientist Avatar answered Feb 24 '23 02:02

rocket scientist