2015-10-08 36 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]