Rails 3.1,has_many关系和新记录问题
假设我在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论