Azalar
Azalar

Reputation: 177

Passing parameters via url

How do I pass parameters to a Rails application using a normal web url?

For instance if I have..

http://0.0.0.0:3000/lists/create/list[name]=Paul&list[age]=39&list[tag]=misc

So I have created a controller called lists and I want to pass a name, age and a tag..

In my example I am passing..

name = Paul age = 39 tag = misc

My example I pasted above says that the item was created but the item it adds has empty data, suggesting my formatting isn't correct.

Could anyone tell me how I structure the url above to pass the parameters correctly?

Thanks Paul

Upvotes: 1

Views: 4521

Answers (1)

Benjamin Manns
Benjamin Manns

Reputation: 9148

By default, Rails's RESTful routing prohibits the create action via the GET (regular url) protocol. For your specific example, you would need to add this route to your config/routes.rb file:

map.create_list 'list/create', :controller => 'lists', :action => 'create', :conditions => { :method => :get }

This adds a route create_list_path or create_list_url that is accessible via GET for links, etc. The url used to create a list directly would be:

http://0.0.0.0:3000/lists/create?list[name]=Paul&list[age]=39&list[tag]=misc

Also note that if you are getting errors about invalid authenticity tokens, you may need to add this line to your controller:

skip_before_filter :verify_authenticity_token, :only => :create

For more general cases, you configure routes similarly and forms as follows:

You need to specify :method => 'get' in your form_tag.

This is discussed in the Ruby on Rails Form Helpers guide (search for "A Generic Search Form").

The basic code given that should get you started is

<%= form_tag(search_path, :method => "get") do %>
  <%= label_tag(:q, "Search for:") %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("Search") %>
<% end %>

generates

<form action="/search" method="get">
  <label for="q">Search for:</label>
  <input id="q" name="q" type="text" />
  <input name="commit" type="submit" value="Search" />
</form>

which GETs the url: http://my.server/search?q={query input}&commit=Search.

Upvotes: 3

Related Questions