![](/img/trans.png)
[英]Chaining multiple scopes with different joins to same table in squeel
[英]Referencing different names in joins with scopes
我有一个多态关联,有时我想预加载它的关联。 当我离开加入 model 时,我的 WHERE 过滤器会丢失,因为它们没有引用命名关联。
SELECT COUNT(*) FROM `companies` LEFT OUTER JOIN `key_values` `latest_information` ON `latest_information`.`attachment_id` = `companies`.`id` AND `latest_information`.`attachment_type` = 'Company' AND `key_values`.`name` = 'latest_information' WHERE `latest_information`.`id` IS NOT NULL
# => ActiveRecord::StatementInvalid: Mysql2::Error: symbol key_values.`name` not found
这是生成的查询,但由于未引用 key_values.name 而无效。
这是我的 model 的样子:
class Company < LeadRecord
has_many :key_values, as: :attachment, dependent: :delete_all
has_one :latest_information,
-> { KeyValue.latest('latest_information') },
class_name: KeyValue.to_s,
as: :attachment
end
class KeyValue < LeadRecord
belongs_to :attachment, polymorphic: true
def self.latest(name)
order(created_at: :desc).where(name: name) # This is the source of the error
end
end
我可能可以通过将附加参数传递给self.latest
来解决这个问题,例如关联名称,但我想知道是否有更好的 Rails 方法来做到这一点。
在此期间,我通过对 KeyValue 进行此更改来解决此问题。
# key_value.rb
def self.latest(name, association_name = 'key_values')
order(created_at: :desc).where("#{association_name}.name = ?", name)
end
# company.rb
has_one association_name,
-> {
KeyValue.latest(
method_name.to_s,
association_name.to_s,
)
},
class_name: KeyValue.to_s,
as: :attachment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.