ruby on rails 3 - Query using condition within an array -


i have 2 models, user , centre, have many many relationship.

class user < activerecord::base   attr_accessible :name   has_and_belongs_to_many :centres  end  class centre < activerecord::base   attr_accessible :name, :centre_id, :city_id, :state_id   has_and_belongs_to_many :users  end     

now have user multiple centres, , want retrieve centres have same "state_id" user.

this doing now

state_id_array = [] user.centres.each |centre|   state_id_array << centre.state_id end return centre.where("state_id in (?)", state_id_array).uniq 

it works, it's ugly. there better way achieving this? ideally 1 line query.

update

now have

centre.where('centres.state_id in (?)', centre.select('state_id').joins(:user).where('users.id=(?)', user)) 

the subquery work itself, when tried execute entire query, null inner query.

centre.select('state_id').joins(:user).where('users.id=(?)', user) 

will generate

 select state_id "centres" inner join "centres_users" on "centres_users"."centre_id" = "centres"."id" inner join "users" on "users"."id" = "centres_users"."user_id" (users.id = (5)) 

which return 'sa', 'vic', 'vic'

but whole query generate

 select distinct "centres".* "centres" (centres.state_id in (null,null,null))  

does user has state_id column if yes try this, user.joins("left outer join users on users.state_id = centers.state_id") else try user.joins(:center)


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -