mercredi 22 juillet 2015

Ruby on Rails 3, query using condition within an array

I have 2 models, user and centre, which have a many to 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 I have an user with multiple centres, and I want to retrieve all the centres that have the same "state_id" as that user.

This is what I am doing now

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

It works, but it's very ugly. Is there a better way for achieving this? Ideally a one line query.

Aucun commentaire:

Enregistrer un commentaire