2012-02-03 44 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

相关问题