Rails has_many 与 finder_sql 和 name_scope 组合返回 nil
例如,假设您有:
class Model < AR::Base
has_many :somethings, :finder_sql => "SELECT * FROM somethings"
end
class Something < AR::Base
named_scope :valuable {...code...}
end
# Assume you have one model but 0 somethings:
# Model.first.somethings # => [] Good!
# Model.first.somethings.valuable # => nil Bad! Should return [] !!!
仅当您在 has_many 关系中有 finder_sql 时才会发生这种情况。在其他情况下,它会按预期工作。
这是 Rails 2.3.14 的正常行为吗?
For example lets say you have:
class Model < AR::Base
has_many :somethings, :finder_sql => "SELECT * FROM somethings"
end
class Something < AR::Base
named_scope :valuable {...code...}
end
# Assume you have one model but 0 somethings:
# Model.first.somethings # => [] Good!
# Model.first.somethings.valuable # => nil Bad! Should return [] !!!
This only occurs when you have finder_sql in has_many relationship. In other cases it works as expected.
Is this normal behavior of Rails 2.3.14?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,如果您指定finder_sql,那么您将无法附加范围。这是因为 finder_sql 适用于不符合正常 activeRecord 范例的情况。话虽如此,您的构建方式是不正确的。您不需要在这样的关系中存储没有过滤器的 select * 。关系的目的是将过滤器应用于另一个模型。因此, Model.find(params[:id]).somethings 的方式与调用 Something.all 完全相同。在后一种情况下,作用域将适用于您,因为 .all 可以限定作用域。
yes, if you specify finder_sql, then you will not be able to append scopes. that's because finder_sql is for situations that do not fit the normal activeRecord paradigm. That being said, the way you have this constructed is incorrect. you should not need to store a select * with no filters in a relationship like that. the purpose of a relationship is to apply a filter to the other model. so, the way you have it Model.find(params[:id]).somethings is exactly the same as calling Something.all . the scope will work for you in the latter case because .all can be scoped.