gpt4 book ai didi

ruby-on-rails - rails : using associated model's columns in :where

转载 作者:行者123 更新时间:2023-12-04 06:36:34 25 4
gpt4 key购买 nike

我不确定这里发生了什么。我有一个我正在尝试创建的范围,它适用于我的协会:

class Subscription < ActiveRecord::Base
belongs_to :subscriber, :class_name => "User"
belongs_to :subscribable, :polymorphic => true
end

create_table :products do |t|
t.string :name
t.decimal :price
t.decimal :cost_per_unit
t.integer :user_id
end

create_table :subscriptions do |t|
t.string :name
t.decimal :price
t.decimal :cost_per_unit
t.integer :subscriber_id
t.integer :subscribable_id
t.string :subscribable_type
end

class Product < ActiveRecord::Base
has_many :subscriptions, :as => :subscribable, :dependent => :destroy

def self.lower_prices
Product.includes(:subscriptions).
where("products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit" )
end
end

我正在尝试将产品的较低价格与订阅进行比较,但这给了我错误:

ActiveRecord::StatementInvalid in Pages#subscribed_products

PGError: ERROR: missing FROM-clause entry for table "subscriptions"
LINE 1: ... WHERE (user_id != 2) AND (products.price < subscripti...
^
: SELECT COUNT(*) FROM "products" WHERE (user_id != 2) AND (products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit)

这里有什么问题吗?

最佳答案

includes 方法并不完全符合您的想法。将 joins 替换为 includes,它应该按照您的意思执行:

Product.joins(:subscriptions).
where("products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit" )

或者也许:

Product.includes(:subscriptions).joins(:subscriptions).
where("products.price < subscriptions.price OR products.cost_per_unit < subscriptions.cost_per_unit" )

joins 在生成的 SQL 查询中转换为 JOIN,因此您可以在连接表上执行 WHERE 子句。 include 只是要求 Active Record 执行另一个查询以选择给定表中的所有相关记录。如果同时执行这两个操作,Active Record 会创建一个(相当长的)一体机,它连接两个表并使用结果创建两组对象。

关于ruby-on-rails - rails : using associated model's columns in :where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10097358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com