2015-10-08 35 views
0

我想通过它的:id找到Blog,然后select只有它的几个属性。Rails查询:按ID查找第一条记录并仅选择该记录的指定属性

实施例:

# 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) 

This post建议使用where代替find。但据我所知,where在我的场景中是效率低下的,因为它继续在数据库中搜索更多匹配,即使它发现我想抓取的唯一记录。

我该如何指定抓住它找到的第一条记录,然后只抓取选定的属性?

回答

5

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

+0

啊!我想订单在这里很重要。谢谢。 – Neil

+0

欢迎您! – nsave

1

@ n保存的答案可能是你最好的选择。

如果出于某种原因,你要保持你的顺序(select后来去),你可以做到以下几点:

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

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