【发布时间】:2012-08-16 23:33:03
【问题描述】:
我正在尝试为我的应用程序编写一个通用排序库,但遇到了一些问题。我的class WorkOrder 中有一个范围定义,如下所示:
scope :join, lambda {|join_model, sort_direction, sort_by| {:joins => join_model, :order => sort_by + " " + sort_direction}}
join_model作为参数传递给控制器,控制器根据传入的参数向模型询问排序列表。很简单……
@work_orders = @order.work_orders.join_to({:product_configuration => :product}, "ASC", "item").all
这对于 WorkOrders belongs_to :product_configuration 和 ProductConfigurations belongs_to :product 非常有效。
但如果我想这样称呼它:
work_orders = @order.work_orders.join_to("worker", "ASC", "item").all
或
work_orders = @order.work_orders.join_to(:worker, "ASC", "item").all
我得到一个错误。我确定你想知道 WorkOrders belongs_to :worker
总而言之,当我尝试转到http://localhost:3000/foo?direction=ASC&join_to=worker&sort=name 时,我收到以下错误:
ActiveRecord::StatementInvalid in FooController#index
PG::Error: ERROR: invalid reference to FROM-clause entry for table "work_orders"
LINE 1: SELECT "work_orders".* FROM "work_orders" worker WHERE (work...
任何建议都将不胜感激,因为我对 Ruby 和 Rails 还比较陌生。
更新
如果我将范围定义更改为
scope :join, lambda {|join_model, sort_direction, sort_by| {:joins => join_model.to_sym, :order => sort_by + " " + sort_direction}}
当我导航到 http://localhost:3000/foo?direction=ASC&join_to=worker&sort=name 时没有收到错误消息,但当我导航到 http://localhost:3000/pretzel?direction=ASC&join_to%5Bproduct_configuration%5D=product&sort=item 时却收到了
错误信息是
undefined method `to_sym' for {"product_configuration"=>"product"}:ActiveSupport::HashWithIndifferentAccess
【问题讨论】:
-
表名是多义化的,你试过用
workers吗? -
谢谢@Matzi!但这不起作用,因为这不是 SQL 命令,而是 rails 范围定义。
-
您使用的是哪个版本的 Rails?
-
另外,你能发布你的模型代码,声明
Worker和WorkOrder之间的belongs_to关系吗? -
@Brandan Rails 3.2.3 ruby-1.9.3 'class WorkOrder
标签: ruby-on-rails activerecord join parameters scope