为什么不能将包含"row objects"数组的变量传递给 Rails 中的 .excluding/.where.not 方法?



我目前正在学习ActiveRecord并通过RSpec中的一些测试练习工作。
下面是让我困惑的测试的缩写版本。

我可以通过将results变量更改为results = Row.where.not(id: rows_not_included)来传递它,但是我无法理解为什么你不能将保存行对象的变量传递给.excluding方法并获得预期的结果,而不具体引用列?
我考虑的是"行对象"吗?错了,还是还有什么我不明白的地方?为什么需要引用一个特定的列来按照预期的方式阅读这个参数?为什么Rails可以理解一个指向表中行的实例变量数组是什么,当它在期望内部时,但是不是,当它作为ActiveRecord查询的参数传递时?

Rails v: 5.2.4

@row_1 = Row.create(:blah, :blah_blah)
@row_2 = Row.create(:blah, :blah_blah)
@row_3 = Row.create(:blah, :blah_blah)
@row_4 = Row.create(:blah, :blah_blah)
rows_not_included = [@row_1, @row_3]
expected_result = [@row_2, @row_4]
results = Row.excluding(rows_not_included)
# ----->  Row.where.not(rows_not_included) produces the same results; see below
expect(results).to eq(expected_result)

.where.not:

输出错误
[1] pry(#<RSpec::ExampleGroups::ActiveRecordObstacleCourseWeek2>)> Item.where.not(items_not_included)NoMethodError: undefined method `include?' for #<Item:0x00007fa61caa1e90>
from /Users/brennastuart/.rbenv/versions/2.7.4/lib/ruby/gems/2.7.0/gems/activemodel-5.2.8/lib/active_model/attribute_methods.rb:430:in `method_missing'

. exclude输出错误:

[4] pry(#<RSpec::ExampleGroups::ActiveRecord>)> Item.excluding(items_not_included)
NoMethodError: undefined method `excluding' for #<Class:0x00007fcab2853ea8>
from /Users/brennas/.rbenv/versions/2.7.4/lib/ruby/gems/2.7.0/gems/activerecord-5.2.8/lib/active_record/dynamic_matchers.rb:22:in `method_missing'

当你分配这样的结果时,你说测试通过了,对吗?

results = Row.where.not(id: rows_not_included)

上面的查询将搜索id不同于作为参数给出的对象id的行。如果您指定了一个列名,那么rails将尝试使用包含您指定的列的where条件进行查询,并将其与给定对象的id属性进行比较。我刚刚尝试了一些场景,发现了这个

results = Row.where.not(name: rows_not_included)

上面的代码将比较数据库中行记录的name列与rows_not_included对象的id。

最新更新