【问题标题】:Active record query with foreign key带外键的活动记录查询
【发布时间】: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


    【解决方案1】:

    您使用了错误的表名。没有名为“类别”的表。

    我认为应该是这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 2016-03-10
      • 2013-02-01
      相关资源
      最近更新 更多