【发布时间】:2013-09-10 12:23:38
【问题描述】:
我有一个具有 has_many 关联的模型:Charts has_many ChartConditions
图表模型具有以下字段:
- 姓名(职务)
- 表名(型号)
chart_conditions 模型具有用于
的字段- assoc_name(到 .joins)
- 名称(列)
- 值(值)
- 运算符(运算符
基本上,我的图表告诉我们要在哪个模型上运行动态查询(使用 table_name 字段)。然后 Chart 的 chart_conditions 将告诉我们该模型中的哪些字段要排序。
所以在我将要查询的模型中,我需要使用多个 chart_conditions 动态构建 where 子句。
您可以在下面看到我首先根据所有对象的 assoc_name 字段进行连接
我想出的例子。这有效,但不适用于名称/值的动态运算符,并且还会引发弃用警告。
def self.dynamic_query(object)
s = joins(object.map{|o| o.assoc_name.to_sym})
#WORKS BUT GIVES DEPRECATED WARNING (RAILS4)
object.each do |cond|
s = s.where(cond.assoc_name.pluralize.to_sym => {cond.name.to_sym => cond.value})
end
end
然后我怎样才能将我的动态运算符值添加到此查询中?还有为什么我不能说:
s = s.where(cond.assoc_name.pluralize : {cond.name : cond.value})
我必须使用 => 和 .to_sym 才能让它工作。上述语法错误:syntax error, unexpected ':' ...ere(cond.assoc_name.pluralize : {cond.name : cond.value}) ... ^
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 activerecord