Rails 3.1,has_many关系和新记录问题

发布于 2024-12-04 20:19:53 字数 891 浏览 2 评论 0原文

假设我在 model_1 和 model_2 之间有一个简单的 has_many 关系:

class Model1 < ActiveRecord::Base
    has_many :models_2
end

class Model2 < ActiveRecord::Base
    belongs_to :model_1
end

现在,我通过该关系创建 Model2 的实例:

irb>m1 = Model1.first
irb>m2 = m1.models_2.new

现在,如果我想询问关系的大小,Rails 3.0.x 和 Rails 3.1 之间存在巨大差异。

按照前面的示例,在 Rails 3.0.x 中,我得到:

irb>m1.models_2.any?
irb>false
irb>m1.models_2.size
irb>0

这意味着,不考虑新对象

Rails 3.1 中的查询完全相同:

irb>m1.models_2.any?
irb>true #OMG!!
irb>m1.models_2.size
irb>1

所以,解决方案是:

irb>m1.models_2.all.any?
irb>false
irb>m1.models_2.all.size
irb>0

如果我必须改变与 .all 的所有关系,我就有大麻烦了......对这种情况有什么想法吗?非常感谢。

Supose I have a simple has_many relationship betwen model_1 and model_2:

class Model1 < ActiveRecord::Base
    has_many :models_2
end

class Model2 < ActiveRecord::Base
    belongs_to :model_1
end

Now, I create an instance of Model2 through the relationship:

irb>m1 = Model1.first
irb>m2 = m1.models_2.new

Now, if I want to ask for the size of the relationship, there's a huge difference between Rails 3.0.x and Rails 3.1.

Following the previous example, in Rails 3.0.x i get:

irb>m1.models_2.any?
irb>false
irb>m1.models_2.size
irb>0

This means, new objects are not being considered

This exact same query in Rails 3.1:

irb>m1.models_2.any?
irb>true #OMG!!
irb>m1.models_2.size
irb>1

So, the solution is:

irb>m1.models_2.all.any?
irb>false
irb>m1.models_2.all.size
irb>0

If I have to change ALL my relationships with .all, I'm in a big trouble... any ideas about this situation? Thank you very much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文