【发布时间】:2020-06-09 11:44:33
【问题描述】:
我有一个类别模型:
class Category < ApplicationRecord
has_many :products
end
使用此数据库架构:
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
还有一个产品模型:
class Product < ApplicationRecord
belongs_to :category
end
使用此数据库架构:
create_table "products", force: :cascade do |t|
t.string "origin"
t.string "name"
t.text "description"
t.bigint "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["category_id"], name: "index_products_on_category_id"
end
在我的种子中,我只有 2 个类别(“咖啡”和“设备”),并且一些产品已经播种了类别:咖啡。 我正在尝试在我的家庭控制器中进行简单的活动记录查询,以仅选择具有咖啡类别名称的产品。 我试过了:
@coffees = Product.joins(:category).where("name = 'coffee'")
和
@coffees = Product.joins(:category).where("category.name = 'coffee'")
和
@coffees = Product.where("product.category.name == 'coffee' ")
但它们都不起作用,我无法在我的主视图上显示数组。有什么想法吗?
【问题讨论】:
标签: sql activerecord foreign-keys ruby-on-rails-5