Ruby on rails 如何将url参数传递给rails3中的模型?

Ruby on rails 如何将url参数传递给rails3中的模型?,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我有一个find_by_sql语句,我正试图将位置id传递给它。我想我可以这样做: 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}'")

我有一个find_by_sql语句,我正试图将位置id传递给它。我想我可以这样做:

  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'参数随请求一起发送,但我不知道如何从模型中调用。如果可能的话?

您不能从Rails模型访问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
或者更好的是,Rails3中类似的东西更干净。此外,这将从SQL注入中转义location_id参数

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

开始时不需要位置,因为这是当前模型。如果关联正确,则可以使用joins作用域链接这些表,只需将所需参数传递到其中,

您无法从Rails模型访问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
或者更好的是,Rails3中类似的东西更干净。此外,这将从SQL注入中转义location_id参数

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

开始时不需要位置,因为这是当前模型。如果您的关联正确,您可以使用连接作用域链接这些表,只需将所需参数传递到其中,

这实际上是一个错误:错误的参数数量0表示我的错误,我忘记在我的视图中更改为@location_history.each.do。这实际上是一个错误:错误的参数数量0表示我的错误,我忘记在我的视图中更改为@location\u history.each.do。