导轨 - HAS_ONE关系:作用域关联和非关联的对象 [英] Rails - has_one relationship : scopes for associated and non-associated objects
问题描述
我有这样的关系:用户可以有零或一只狗,但狗有属于别人
I have this relationship : a user can have zero or one dog, but a dog has to belong to someone.
# dog.rb
class Dog < ActiveRecord::Base
belongs_to :user
end
# user.rb
class User < ActiveRecord::Base
has_one :dog
end
我要定义的范围如下:
I want to define the following scopes :
User.with_a_dog
User.without_a_dog
我能做到这一点的第一种情况,因为联接INNER默认情况下轨JOIN:
I can do this for the first case, because the joins are INNER JOIN by default in rails :
scope :with_a_dog, :joins(:dog)
1 /这是解决方案的第一个范围不够好?
1/ Is this solution for the first scope good enough?
2 /你会怎么做第二个?
2/ What would you do for the second one?
3 /(有点关系)是否有这样做的更好的办法?
3/ (Somewhat related) Is there a better way of doing this? :
# user.rb
def has_a_dog?
!self.dog.nil?
end
感谢您的帮助!
Thanks for your help!
推荐答案
有关问题2我认为下面应该工作:
For question 2 I think the following should work:
scope :without_a_dog include(:dog), where('dogs.id is null')
如果有应该做一个LEFT JOIN这意味着那里没有狗的关系加入到用户的dogs.id栏为空。
Where include should do a left join meaning that where there's no dog relation to join to the user the dogs.id column should be null.
这篇关于导轨 - HAS_ONE关系:作用域关联和非关联的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!