Search code examples
ruby-on-railsroutesruby-on-rails-2ruby-1.8.7

Passing Non-ID Variable Through Rails Routes


Rails 2.3, Ruby 1.8.7

I'm trying to pass a variable through a rails route. I haven't been able to find a case where anyone was doing this with something that wasn't an id of a model. I'm not certain if that's the source of the problem.

In the view:

reference_string = "string of random letters and numbers"
something_path(reference_string)

In routes.rb:

map.something 'something/:reference_string', :controller => :my_controller, :action => "my_action", :reference_string => "reference_string"

In my_controller:

def my_action(reference_string)
  ...
end

I end up getting an Argument Error:

wrong number of arguments (0 for 1)

Thanks in advanced


Solution

  • Controller actions do not accept arguments.

    Update your controller action so it looks like this:

    def my_action
      ...
    end
    

    Then, to access reference_string, try params[:reference_string] anywhere in the controller or views. As an example, you could do this:

    def my_action
      redirect_to root_url, :notice => "You sent us the reference string #{params[:reference_string]}!"
    end