Ruby on rails rails 4作用域通过多个has_-one关联
我试图通过两层has_-one关联获得一个activerecord关联,但我无法完全理解它 我有3种型号:Ruby on rails rails 4作用域通过多个has_-one关联,ruby-on-rails,activerecord,scope,Ruby On Rails,Activerecord,Scope,我试图通过两层has_-one关联获得一个activerecord关联,但我无法完全理解它 我有3种型号: class Dialog < ActiveRecord::Base belongs_to :contact end class Contact < ActiveRecord::Base has_many :dialogs belongs_to :location end class Location < ActiveRecord::Base has_m
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
我可以使用select获得所需结果的非activerecord数组:
Dialog.all.select{|s| s.contact.location_id == Location.first.id }
但是我需要它来返回一个activerecord数组,以便可以对结果调用其他作用域或类方法。我曾经尝试过使用连接和包含,但是在阅读了rails指南之后,我感到困惑
有人能帮我弄清楚如何构造一个作用域或类方法来实现这一点吗
提前感谢您可以按如下方式定义范围:
class Dialog < ActiveRecord::Base
belongs_to :contact
scope :from_location, -> (id) do
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) do
where(location_id: id)
end
end
类对话框只需在您接受的答案中添加一条注释,引用ruby on rails指南网站: 使用类方法是接受作用域参数的首选方法。这些方法仍然可以在关联对象()上访问 因此,在您的条件下,不要使用参数来定义作用域,而是定义一个方法:
class Contact < ActiveRecord::Base
has_many :dialogs
belongs_to :location
def self.from_location(id)
where(location_id: id)
end
end
class联系人
class Contact < ActiveRecord::Base
has_many :dialogs
belongs_to :location
def self.from_location(id)
where(location_id: id)
end
end