问题描述
我将尝试解释:
我有一个表产品"和一个表商店".我试图只让商店名称显示在页面上,但ActiveRecord会向我返回商店中的所有列.
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.
这是代码:
@product = Product
.order(id: :desc)
.includes(:store)
.select("products.id, products.store_id, stores.name")
.limit(1)
内置查询(来自Rails):
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)
我只想显示产品的商店名称,但是Rails选择了所有商店列.
I just want to show the product's store name, but Rails is selecting all the store columns.
我的模特:
Product.rb
Product.rb
class Product < ActiveRecord::Base
belongs_to :store, :foreign_key => 'store_id'
end
Store.rb:
class Loja < ActiveRecord::Base
has_many :products
end
有什么主意吗?
推荐答案
您可以通过采摘和加入来做到这一点:
You can do this via pluck and joins:
Product
.order(id: :desc)
.joins(:store)
.pluck("products.id, products.store_id, stores.name")
.limit(1)
您将获得一个数组,该数组遵循pluck中定义的列的顺序.如果您不熟悉拔毛,我已经写过有关拔毛的文章.
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.
另一种方法是通过直接的SQL查询:
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, ... }]
两个选项都产生相同的SQL语句,只是结果的显示方式有所不同.
Both options produce the same SQL statement, the just vary in how the results come out.
这篇关于Rails仅包含关联中的选定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!