2012-08-16 71 views
1

我正在嘗試爲我的應用程序編寫一個通用的排序庫,並且遇到了一些問題。我有我的class WorkOrder內的範圍定義,看起來像這樣:將參數傳遞給作用域定義Ruby on Rails

scope :join, lambda {|join_model, sort_direction, sort_by| {:joins => join_model, :order => sort_by + " " + sort_direction}} 

join_model作爲一個參數去誰問基於params中傳遞的排序列表模式控制器傳遞。夠簡單了...

@work_orders = @order.work_orders.join_to({:product_configuration => :product}, "ASC", "item").all 

這工作得很好的工作訂單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 

我得到一個錯誤。我相信你要知道,工作訂單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 
+0

名稱prularized表,你使用它與'workers'試過嗎? – Matzi 2012-08-17 10:14:37

+0

謝謝@Matzi!但是這不起作用,因爲這不是SQL命令,而是一個rails範圍定義。 – Shawnzam 2012-08-17 15:32:17

+0

您正在使用哪個版本的Rails? – Brandan 2012-08-17 15:48:43

回答

0

嘗試將此作用域重寫爲類方法,並使用ActiveRecord::QueryMethods中的方法而不是舊的散列樣式語法。我能夠在虛擬應用程序中獲得與此類似的東西。

def self.join_to(join_model, sort_column, sort_direction = 'ASC') 
    joins(join_model).order("#{sort_column} #{sort_direction}") 
end 
+0

如何傳入join_model?像'{:product_configuration =>:product}'一樣? – Shawnzam 2012-08-17 18:37:52

0

我能解決這個問題。沒有必要加入WorkOrdersWorkers。我只需通過nil就可以得到需要排序的連接的列。

def self.join_to(join_model, sort_direction = 'ASC', sort_column) 
    if join_model == 'nil' 
     order("#{sort_column} #{sort_direction}") 
    else 
     joins(join_model).order("#{sort_column} #{sort_direction}") 
    end 
    end 

,我只是通過worker_idsort_column

感謝, 肖恩

相關問題