simonmorley
simonmorley

Reputation: 2804

How is it possible to pass a url parameter to the model in rails3?

I've got a find_by_sql statement which I'm trying to pass the location id to. I thought I could do something like this:

  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

I figured the following would pull the id parameter from the url:

 a.location_id = '#{id}'

However that throws an error about an undefined variable.

I can see the id => '2' parameter being send with the request but I don't know how to call from the model. If at all possible?

Upvotes: 1

Views: 158

Answers (1)

Blake Simpson
Blake Simpson

Reputation: 1088

You cannot access the "params" hash from a Rails model. Params are only for your controller and views to interact.

You can pass the value you need from the controller to the model with something like this instead:

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

and in controller:

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

Or better yet, something like this in Rails 3 is way cleaner. Also, this will escape the location_id parameter from SQL injection.

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

You do not need "Location" at the beginning because that is the current model. If your associations are correct, you can use the "joins" scope to link these tables and just pass the parameter you need to "where",

Upvotes: 4

Related Questions