带外键的活动记录查询

5lwkijsr  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(274)

我有一个分类模型:

class Category < ApplicationRecord
    has_many :products
end

使用此db架构:

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

使用此db架构:

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

在我的种子里,我只有两个类别(“咖啡”和“设备”),有些产品的种子是咖啡。我正在尝试在我的家庭控制器中进行一个简单的活动记录查询,以便只选择类别名称为coffee的产品。我试过:

@coffees = Product.joins(:category).where("name = 'coffee'")

@coffees = Product.joins(:category).where("category.name = 'coffee'")

@coffees = Product.where("product.category.name == 'coffee' ")

但是它们都不起作用,我无法在主视图上显示数组。你知道吗?

daupos2t

daupos2t1#

您使用了错误的表名。没有名为“category”的表。
我想应该是这样的:

@coffees = Product.joins(:category).where("categories.name = 'coffee'")

相关问题