Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails 4作用域通过多个has_-one关联_Ruby On Rails_Activerecord_Scope - Fatal编程技术网

Ruby on rails rails 4作用域通过多个has_-one关联

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

我试图通过两层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_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
类对话框(id)do 其中(contact\u id:contact.from\u location(id)。选择(:id)) 结束 结束 类联系人(id)do 其中(位置\u id:id) 结束 结束
只需在您接受的答案中添加一条注释,引用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