我有这种关系:用户可以拥有零只或一只狗,但是狗必须属于某人。
# 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
感谢您的帮助!
答案 0 :(得分:4)
只是想添加这个,以防有人发现它有用:
class User < ActiveRecord::Base
has_one :dog
# To get records with a dog we just need to do a join.
# AR will do an inner join, so only return records with dogs
scope :with_a_dog, -> { joins(:dog) }
# To get records without a dog, we can do a left outer join, and then only
# select records without a dog (the dog id will be blank).
# The merge with the Dog query ensures that the id column is correctly
# scoped to the dogs table
scope :without_a_dog, -> {
includes(:dog).merge( Dog.where(:id => nil) )
}
end
class Dog < ActiveRecord::Base
belongs_to :user
end
答案 1 :(得分:1)
对于问题2,我认为以下内容应该有效:
scope :without_a_dog include(:dog), where('dogs.id is null')
where include应该执行左连接,这意味着如果没有狗关系连接到用户,dogs.id列应为null。
答案 2 :(得分:1)
scope :without_a_dog, -> {
includes(:dog).select { |user| user.dog.nil? }
}