Rails include only selected columns from relation

蓝咒 提交于 2021-02-06 10:21:30

问题


I will try to explain:

I have a table 'Product' and a table 'Store'. I'm trying to get just the store name to show at the page, but ActiveRecord is returning me all the columns from the store.

Here is the code:

@product = Product
          .order(id: :desc)
          .includes(:store)
          .select("products.id, products.store_id, stores.name")
          .limit(1)

The built query (from Rails):

Processing by IndexController#index as HTML
Product Load (0.0ms)  SELECT  products.id, products.store_id FROM `products`  ORDER BY `products`.`id` DESC LIMIT 1
Store Load (1.0ms)  SELECT `stores`.* FROM `stores` WHERE `stores`.`id` IN (111)

I just want to show the product's store name, but Rails is selecting all the store columns.

My models:

Product.rb

class Product < ActiveRecord::Base
  belongs_to :store, :foreign_key => 'store_id'
end

Store.rb:

class Loja < ActiveRecord::Base
  has_many :products
end

Any idea?


回答1:


You can do this via pluck and joins:

Product
  .order(id: :desc)
  .joins(:store)
  .pluck("products.id, products.store_id, stores.name")
  .limit(1)

You're going to get an array back that follows the order of the columns defined in pluck. I've written about pluck before if you're not familiar with it.


The other way is via a straight SQL query:

sql =<<-EOF
  SELECT products.id, products.store_id, stores.name
  FROM products INNER JOIN stores
    ON products.store_id = stores.id
  ORDER BY products.id DESC
  LIMIT 1
EOF
records = ActiveRecord::Base.connection.execute(sql)

#=> [{"id" => X, "store_id" => Y, "name" => Z, ... }]

Both options produce the same SQL statement, the just vary in how the results come out.




回答2:


Just tried something similar to this on my project. This should work:

@products = Product.
  .order(id: :desc)
  .joins(:store)
  .select("products.id, products.store_id, stores.name")
  .limit(1)

Using joins as opposed to includes will make rails perform only one query, because joins doesn't eager-load the association.



来源:https://stackoverflow.com/questions/32925554/rails-include-only-selected-columns-from-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!