activerecord - rails 4 scope through multiple has_one associations -
i trying activerecord association through 2 layers of has_one associations , cannot quite figure out.
i have 3 models:
class dialog < activerecord::base belongs_to :contact end class contact < activerecord::base has_many :dialogs belongs_to :location end class location < activerecord::base has_many :contacts end
i create scope in dialog model allows me pass in id of location , dialogs created contacts given location... like:
dialog.from_location(location.first.id)
i can non-activerecord array of desired result using select:
dialog.all.select{|s| s.contact.location_id == location.first.id }
but need return activerecord array other scopes or class methods can called on result. have tried using joins , includes, confused after reading rails guides on how use them.
can me figure out how construct scope or class method accomplish this?
thanks in advance
you can define scopes follows:
class dialog < activerecord::base belongs_to :contact scope :from_location, -> (id) where(contact_id: contact.from_location(id).select(:id)) end end class contact < activerecord::base has_many :dialogs belongs_to :location scope :from_location, ->(id) where(location_id: id) end end
Comments
Post a Comment