9

I have a form:

  %form{:action:method => "post"}
    %fieldset
      %label{:for => "title"} Title:
      %input{:name => "title", :type => "text", :value => ""}/
      %label{:for => "notes"} Notes:
      %input{:name => "notes", :type => "text", :value => ""}/
    %a.finish{:href => "/rotas", :method => "post"} Finish!

However, the link does not seem to want to work - maybe I am missing something basic in Haml, or in Rails.

I have a :resource rotas in my routes.rb and my controller has a def create method.

Any help is appreciated! Thanks!

btw. I generated using scaffold - and it seems that the same form is used for edit a model and for a creation. How does it know whether to do a POST or a PUT?

Karan
  • 13,724
  • 24
  • 84
  • 153
  • Note: I updated my answer, I thought the problem was simple at first then realized you had more issues going on. – Andrew May 01 '12 at 21:02

2 Answers2

10

1) You want to put the target of the form in the action:

%form{ :action => "/rotas", :method => "post" }

2) You want a submit button, not a link. Try this:

%input{ :type => "submit" } Finish!

Also, I'm not sure why you're putting a / after your inputs, that's not needed for anything. I don't think it hurts, but I see no reason to include it.

3) Lastly, the Rails convention is not to use haml elements but rather form helpers, which would look like this:

= form_tag '/rotas' do
  = field_set_tag do
    = label_tag :title, 'Title:'
    = text_field_tag :title
    = label_tag :notes, 'Notes:'
    = text_field_tag :notes
    = submit_tag 'Save Changes'

One reason for this is Rails is going to include a hidden Authenticity Token field in the form for you, and normally Rails controllers won't accept forms that are submitted without this authenticity token value. This is to prevent Cross-Site Request Forgery.

Try this and see what you get.

See the FormTagHelper API for reference.

Community
  • 1
  • 1
Andrew
  • 40,445
  • 46
  • 172
  • 276
  • that did not do it - however, I got it working another way ... check out my answer – Karan May 01 '12 at 21:02
  • i just got it working - i have posted it as an answer - what do you reckon? – Karan May 01 '12 at 21:04
  • if you add the submit_tag 'Save Changes' as I have done in my answer ill mark your answer as accepted ;) – Karan May 01 '12 at 21:05
  • Good, glad you got it fixed. I realized twice that there was more important info to add to the answer, so now I think it's at its final version (including submit tag). Sorry to keep changing it on you! – Andrew May 01 '12 at 21:06
  • Lol we're commenting at almost exactly the same time but page loads make these appear out of order. Submit tag is added, thanks for catching that. – Andrew May 01 '12 at 21:08
0

I got it working using the following code:

  = form_tag rotas_path do
    = label :rota, :name, 'Name'
    = text_field :rota, 'name'
    = submit_tag 'Save Changes'
Karan
  • 13,724
  • 24
  • 84
  • 153