Rails include only selected columns from relation

前端 未结 2 1101
一生所求
一生所求 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:59

    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.

提交回复
热议问题