2012-02-03 43 views
1

我有一個find_by_sql語句,我試圖將位置ID傳遞給。我想我可以做這樣的事情:如何將一個url參數傳遞給rails3中的模型?

def self.location_history() 
     Location.find_by_sql("select * from locations a INNER JOIN hotspots b ON a.id = b.location_id INNER JOIN accounts c ON b.mac = c.account_id WHERE a.location_id= '#{id}'") 
    end 

我想通下面將從URL拉id參數:

a.location_id = '#{id}' 

然而拋出約未定義的變量錯誤。

我可以看到與請求一起發送的id =>'2'參數,但我不知道如何從模型中調用。如果可能的話?

回答

4

您不能從Rails模型訪問「params」哈希值。 Params僅適用於您的控制器和視圖進行交互。

你可以通過你的控制器需要的模型是這樣的,而不是價值:

def self.location_history(location_id) 
    Location.find_by_sql("select * from locations a INNER JOIN hotspots b ON a.id = b.location_id INNER JOIN accounts c ON b.mac = c.account_id WHERE a.location_id= '#{location_id}'") 
end 

,並在控制器:

def index 
    @location_history = Location.location_history(params[:id]) 
end 

或者更好的是,這樣的事情在Rails中3是方式更清潔。此外,這將從SQL注入中轉義location_id參數。

def self.location_history(location_id) 
    joins(:hotspots, :accounts).where(:location_id => location_id) 
end 

你並不需要「位置」開頭,因爲它是與當前的模式。如果你的關聯是正確的,你可以使用「連接」範圍來鏈接這些表,只需要將參數傳遞給「where」,

+0

Mucho gracias :) – simonmorley 2012-02-03 09:50:23

+0

這實際上是一個錯誤:「錯誤的參數數量0表示1)「 – simonmorley 2012-02-03 10:01:20

+0

我的錯誤,我忘了在我的視圖中更改爲@ location_history.each.do。 – simonmorley 2012-02-03 10:04:16

相關問題