小编典典

Rails-has_one关系:关联和非关联对象的范围

sql

我有这种关系:一个用户可以有零只或一只狗,但是一只狗必须属于某人。

# dog.rb
class Dog < ActiveRecord::Base
  belongs_to :user
end

# user.rb
class User < ActiveRecord::Base
  has_one :dog
end

我想定义以下范围:

User.with_a_dog
User.without_a_dog

我可以在第一种情况下执行此操作,因为默认情况下,在rails中,联接是INNER JOIN:

scope :with_a_dog, :joins(:dog)

1 /这种针对第一个示波器的解决方案是否足够好?

2 /第二个课程你会做什么?

3 /(有一些关联)是否有更好的方法?:

# user.rb
def has_a_dog?
  !self.dog.nil?
end

谢谢你的帮助!


阅读 233

收藏
2021-04-22

共1个答案

小编典典

对于问题2,我认为以下方法应该有效:

scope :without_a_dog include(:dog), where('dogs.id is null')

其中include应该执行左联接,这意味着在没有狗关系要联接到用户的情况下,dogs.id列应为null。

2021-04-22