最近,我从C#移到了Rails上的ruby,并在rails控制台中检查了记录,在其中我无意中犯了拼写错误。而不是使用find() I used find{}
。它正在工作,但始终返回表中的第一条记录。我不知道这是怎么发生的。
当我用谷歌搜索时,我发现它与阻止有关,但我没有任何想法。
I typed Book.find{3} instead of Book.find(3)
答案 0 :(得分:2)
这是因为当您将一个块传递给find
时,它会返回super
:
def find(*ids) # :nodoc:
# We don't have cache keys for this stuff yet
return super unless ids.length == 1
return super if block_given? ||
primary_key.nil? ...
...
end
然后再次调用find
,不加任何阻止,并将所有其他条件评估为false:
return super unless ids.length == 1
return super if block_given? ||
primary_key.nil? ||
scope_attributes? ||
columns_hash.key?(inheritance_column) && !base_class?
允许它对自身(例如Book)进行查询(限制为1:
)...
statement = cached_find_by_statement(key) { |params|
where(key => params.bind).limit(1)
}
...
然后从对象语句中获取第一个元素,即ActiveRecord :: StatementCache,类似于ActiveRecord :: Relationship对象,其中包含一个或多个属于模型的对象(在本例中为Book):
record = statement.execute([id], connection)&.first
因此,如果将statements
评估为“真”,则将其返回,否则会引发RecordNotFound异常:
record = statement.execute([id], connection)&.first
unless record
raise RecordNotFound.new("Couldn't find #{name} with '#{key}'=#{id}", name, key, id)
end
record
您可以看到此here。