Rails include only selected columns from relation

前端 未结 2 1152
一生所求
一生所求 2021-02-08 04:48

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

2条回答
  •  时光取名叫无心
    2021-02-08 04:49

    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.

提交回复
热议问题