gpt4 book ai didi

sql - Rails - has_one 关系 : scopes for associated and non-associated objects

转载 作者:行者123 更新时间:2023-12-05 00:38:18 29 4
gpt4 key购买 nike

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

# 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

谢谢你的帮助!

最佳答案

只是想添加这个以防有人觉得它有用:

用户名

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

关于sql - Rails - has_one 关系 : scopes for associated and non-associated objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5724000/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com