【问题标题】:Rails 'includes' and 'where' with belongs_to and has_many associationRails 'includes' 和 'where' 与 belongs_to 和 has_many 关联
【发布时间】:2022-07-08 23:26:52
【问题描述】:

我有模型:

`class Order

枚举状态:%i[created in_process]

has_many :order_containers has_many :line_items`

class LineItem < ApplicationRecord

acts_as_paranoid has_paper_trail

枚举状态:%i[in_process collected]

belongs_to :order 属于_to:变体 结束

class Variant < ApplicationRecord

acts_as_paranoid has_paper_trail

has_many :line_items

belongs_to :产品

验证:条形码,存在:真 结束

class Product < ApplicationRecord

acts_as_paranoid has_paper_trail

belongs_to :isles,必填:false has_many :变体

验证:name, :volume, :sku, :price, 存在: true 结束

class Isle < ApplicationRecord

acts_as_paranoid has_paper_trail

has_many :产品 验证:名称,存在:真 结束

我需要编写一个只输出属于该岛的产品的查询

我试试这个@products = Order.includes([:line_items, :variants, :products, :isles]).where('products.isle_id = isle.id').references(:orders),但我得到了错误:

ailure/Error: return { "#{root_name}": [] } if records.blank?
 
 ActiveRecord::StatementInvalid:
   PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "products"
   LINE 1: ..."orders" WHERE "orders"."deleted_at" IS NULL AND (products.i...

如果我设计得不好我很抱歉,我是一个新手开发人员,这是我的第一个任务)

【问题讨论】:

    标签: ruby-on-rails ruby database postgresql activerecord


    【解决方案1】:

    你对它的结构有很多问题。如果您真的只想要特定岛屿的产品,那么您应该可以使用:

    @products = Product.where(isle_id: my_isle_variable)

    【讨论】:

      猜你喜欢
      • 2015-09-11
      • 1970-01-01
      • 2015-04-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多