Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.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中查询具有一对一关联的模型_Ruby On Rails - Fatal编程技术网

Ruby on rails 如何在Rails中查询具有一对一关联的模型

Ruby on rails 如何在Rails中查询具有一对一关联的模型,ruby-on-rails,Ruby On Rails,我想找到所有卡片都属于某个用户,该用户的下一次\u审阅时间在当前time.zone.now之前 下面是我的模式 期望行为 我应该把finder方法保存在相应的模型中 class User < ActiveRecord::Base has_many :cards def next_cards cards.next_cards end end class Card < ActiveRecord::Base has_one :meta def next_car

我想找到所有卡片都属于某个用户,该用户的下一次\u审阅时间在当前time.zone.now之前

下面是我的模式

期望行为

我应该把finder方法保存在相应的模型中

class User < ActiveRecord::Base
  has_many :cards
  def next_cards
    cards.next_cards
  end
end

class Card < ActiveRecord::Base
  has_one :meta
  def next_cards
    # what should I write here?
  end
end

class Meta < ActiveRecord::Base
  belongs_to :card
  # what should I write here?
end
我在想什么

查询元表wherenext\u repeation<今日
 在元模型内部,获取所有目标元 将1个结果加入卡表,以查找目标卡
 内卡模型 返回用户模型内的目标卡
将只返回属于用户的卡片,并且这些卡片具有带有review_date的meta。是否可以将此查询与它所属的模型分开?当然。实际上,我认为最好将此函数与卡作用域分开,而不是像:作用域:下一张卡,->{joins:meta.where'metas.next_review_date如果我需要通过一个限制,哪里是这样做的好地方?限制可能是一个特定的数字或零,返回所有。非常感谢您的响应。最好不要将它放在模型及其范围内,因为这是一个值,在项目的不同部分中可能会有所不同。您可以如果将其放入控制器操作中,只需拨打@user.next\u cards.limit10。再次感谢!您太棒了!
user.cards.joins(:meta).where('metas.next_review_date <= ?', Time.zone.now)
class User < ActiveRecord::Base
  has_many :cards
  def next_cards
    cards.next
  end
end

class Card < ActiveRecord::Base
  has_one :meta
  scope :next, -> { joins(:meta).merge(Meta.next) }
end

class Meta < ActiveRecord::Base
  belongs_to :card
  scope :next, -> { where('next_review_date <= ? ', Time.zone.now) }
end
user.next_cards