Ruby on Rails中where和find在查询时的区别是什么?
- 内容介绍
- 文章标签
- 相关推荐
本文共计333个文字,预计阅读时间需要2分钟。
在探讨Difference Between find and Where with Relationships这个问题时,以下是一些简化的内容:
关于`find`与`where`在关系中的差异,以下是一些关键点。`find`通常用于直接查找特定记录,而`where`则用于构建更复杂的查询条件。在查询`a=Libation.where('user_id=1')`时,`where`方法允许你以更灵活的方式添加条件。
注意:这段内容遵循了不超过100个字的要求,并且尽量简洁明了。
这几乎在 Difference Between find and Where with Relationships回答,但并不完全. (请注意我是如何巧妙地改变问题标题的!)我做查询
a = Libation.where("user_id = 1" ) # gets 10 records b = a.sum("count * weight") # Get right answer c = Libation.where("user_id = 2" ) # gets 8 records d = c.sum("count * weight") # Get right answer
现在我做
e = Libation.all # gets 18 records, good f = e.sum("count * weight") # BOOM! I get NoMethodError (undefined method `+' for #<Libation:0x3b91e88>):
坚果.我试图找到相关的文档,但发现很少.或者我找不到合适的地方.
#where返回一个ActiveRecord :: Relation对象,您可以在其上执行其他方法(例如#sum).但是,#all执行查询返回结果数组,所以当你执行e.sum(…)时,你试图在Array对象而不是ActiveRecord :: Relation对象上执行#sum.您可以尝试使用#scoped代替:
e = Libation.scoped f = e.sum("count * weight")
本文共计333个文字,预计阅读时间需要2分钟。
在探讨Difference Between find and Where with Relationships这个问题时,以下是一些简化的内容:
关于`find`与`where`在关系中的差异,以下是一些关键点。`find`通常用于直接查找特定记录,而`where`则用于构建更复杂的查询条件。在查询`a=Libation.where('user_id=1')`时,`where`方法允许你以更灵活的方式添加条件。
注意:这段内容遵循了不超过100个字的要求,并且尽量简洁明了。
这几乎在 Difference Between find and Where with Relationships回答,但并不完全. (请注意我是如何巧妙地改变问题标题的!)我做查询
a = Libation.where("user_id = 1" ) # gets 10 records b = a.sum("count * weight") # Get right answer c = Libation.where("user_id = 2" ) # gets 8 records d = c.sum("count * weight") # Get right answer
现在我做
e = Libation.all # gets 18 records, good f = e.sum("count * weight") # BOOM! I get NoMethodError (undefined method `+' for #<Libation:0x3b91e88>):
坚果.我试图找到相关的文档,但发现很少.或者我找不到合适的地方.
#where返回一个ActiveRecord :: Relation对象,您可以在其上执行其他方法(例如#sum).但是,#all执行查询返回结果数组,所以当你执行e.sum(…)时,你试图在Array对象而不是ActiveRecord :: Relation对象上执行#sum.您可以尝试使用#scoped代替:
e = Libation.scoped f = e.sum("count * weight")

