Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.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 有没有更好的方法在班级层面上寻找关联?_Ruby On Rails - Fatal编程技术网

Ruby on rails 有没有更好的方法在班级层面上寻找关联?

Ruby on rails 有没有更好的方法在班级层面上寻找关联?,ruby-on-rails,Ruby On Rails,以下是我正在使用的对象: class Client < ActiveRecord::Base has_many :servers def self.active where("updated_at > ?", 1.month.ago) end end class Server belongs_to :client end 我能想到的唯一方法是: def Client.servers Server.where(id: all.collect(&

以下是我正在使用的对象:

class Client < ActiveRecord::Base
  has_many :servers

  def self.active
    where("updated_at > ?", 1.month.ago)
  end
end

class Server
  belongs_to :client
end
我能想到的唯一方法是:

def Client.servers
  Server.where(id: all.collect(&:id))
end

必须有更多的Rails-y才能做到这一点

您想从服务器加入到客户端。像这样的方法应该会奏效:


Server.joins(:client).where('clients.updated_at>?',1.month.ago)

我相信我已经找到了您要查找的内容,这是活动记录方法

在测试过程中,如果您在列中发现与您的
updated_冲突,请确保在您的
活动
范围中消除歧义:

def self.active
  where("clients.updated_at > ?", 1.month.ago)
end

但是我希望能够使用在类Client上定义的查询方法。若我这样做,我要么违反DRY,要么违反封装(通过在服务器上定义它们)。它们只是指导方针。这是基于联接表中的属性查询服务器的方式。另一种选择是从客户端到服务器的一些钝平面映射。
Server.joins(:client).merge(Client.active)
def self.active
  where("clients.updated_at > ?", 1.month.ago)
end