我有这样的关系:一个用户可以拥有零只或一只狗,但狗必须属于某人。
# 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
感谢您的帮助!
只是想添加这个以防有人发现它有用:
user.rb
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
dog.rb
class Dog < ActiveRecord::Base
belongs_to :user
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)