Rails查询:按id查找第一条记录,只选择该记录的指定属性

时间:2015-10-08 16:51:42

标签: ruby-on-rails ruby

我想通过data: { roleIdXXXs: JSON.stringify(rolesChecked) //includeAdministrator: administrator, //includeManager: manager, //includeTechnician: technician, //includeTranscriber: transcriber } 找到Blog,然后:id找到它的几个属性。

示例:

select

This post建议使用# Doesn't work and I don't know why # I want to grab the first blog with this id, and then grab only selected attributes blog = Blog.find(10).select(:id, :title, :date) 代替where。但据我所知,在我的场景中find是低效的,因为它继续在数据库中搜索更多匹配,即使它找到了我想要抓取的唯一记录。

如何指定抓取id找到的第一条记录,然后只抓取所选属性?

3 个答案:

答案 0 :(得分:7)

blog = Blog.select(:id, :title, :date).find(1)

答案 1 :(得分:2)

@ nsave的回答可能是你最好的选择。

如果出于某种原因,您希望保留订单(select稍后进行),您可以执行以下操作:

blog = Blog.where(id: 10).select(:id, :title, :date).first

blog = Blog.where(id: 10).select(:id, :title, :date)[0]

答案 2 :(得分:1)

pick(Rails 6 +)

Rails 6引入了一种新的pick方法。

所以,现在您的问题可以解决

Blog.where(id: 1).pick(:id, :title, :date)

效率甚至更高

Blog.select(:id, :title, :date).find(1)

因为,它将仅加载列值,而不会加载ActiveRecord对象。

有关更多详细信息,请遵循此link to docs

此外,还有一个reference to the corresponding PR