如何解决Rails-检查查询是否未返回结果
以下查询Model.first.model_relation.map(&:another_model).map(&:another_model)
返回[#<ActiveRecord::Associations::CollectionProxy []>]
我也有一个类似的查询,它返回xx条记录。
当我执行上述查询并调用.blank?
时,它返回false。为什么会这样,我如何确定这些查询是否返回记录?
解决方法
给出以下示例模型:
# rails g model country name
class Country < ApplicationRecord
has_many :states
has_many :cities,through: :states
end
# rails g model country name country:belongs_to
class State < ApplicationRecord
belongs_to :country
has_many :cities
end
# rails g model city name state:belongs_to
class City < ApplicationRecord
belongs_to :state
has_one :country,through: :state
end
我们可以通过应用INNER JOIN来获取联接表中具有匹配项的记录:
countries_with_states = Country.joins(:states)
countries_with_cities = Country.joins(states: :cities)
# can be shortened since we have an indirect association
countries_with_cities = Country.joins(:cities)
这将只返回联接表中具有至少一个匹配项的行。
我们还可以通过使用LEFT OUTER JOIN并在连接表上设置条件来获取连接表中不匹配的记录:
countries_with_no_states = Country.left_joins(:states)
.where(states: { id: nil })
countries_with_no_cities = Country.left_joins(:cities)
.where(cities: { id: nil })
不应该在关联上使用#map
,因为它极其无效,并且可能导致严重的性能问题。相反,您需要在模型之间创建有意义的associations,并使用联接过滤数据库中的行。
ActiveSupport的#blank?
和#empty?
方法仅应在处理用户输入(例如字符串和字符串数组)时才真正使用,这是其启发式方法真正有用的地方。
对于记录集合,您有.exists?
会始终创建一个查询,还有.any?
和.none?
会在加载关系后使用大小。
我猜您正在寻找的方法是empty?
,它是在ActiveRecord::Associations::CollectionProxy
上定义的:
empty?()如果集合为空,则返回true。
https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-empty-3F
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。