views:

119

answers:

2

I have the following form_for declaration in a Rails site I am building:

form_for(form_question, :url => { :controller => "form_questions", :action => "edit", :id => form_question.id }) do |f|

but the site renders;

<form action="/form_questions/1/edit">

why is it putting the '/1/' before the "edit" in the action url?

+4  A: 

Simple Answer. RESTful routes.

Basically you have defined resources :form_questions in config/routes.rb and that is transforming, automagically, your URL to make it RESTful.

Tony Fontenot
apparently if i rename the action to "update" it works, go figure.
Ash
yep... `update` becomes a PUT request and it will generate a url of `/form_questions/:id`
Tony Fontenot
Ahh, I get it - I didn't realise that Rails automatically changes the verb of the request based on the method. That explains why 'new' is always posted. lol I feel so stupid. But that's really neat!
Ash
The other aspect is that, assuming the RESTful approach and using scaffolding, the you make a GET request to the edit action which retrieves the item in a form, the form is then PUT to the update action which writes to in the database. There is a similar relationship between new and create, you GET an the new action which returns a blank form and the form is POSTed to the create action to be written to the database.
MattMcKnight
A: 

I would recommend using the RESTful helpers provided to you, like:

<% form_for(@form_question) do %>
  <%= f.text_field :question %>
  ...
<% end %>

Which will generate a URL to either create or update depending on if the @form_question response to new_record? is true or false respectively. It'll also do other things, like give the form tag a different id attribute based also off what new_record? returns.

Ryan Bigg
Yes I am doing this elsewhere, but in this particular case, I am unable to use the @form_question - as its actually looping through a set of records, so this option doesn't really apply. Thanks for the answer though, you've inadvertently answered another question I had about how Rails seems to magically know the difference between create and edit.
Ash