Search code examples
ruby-on-railsbuttonformtastic

Rails , Formtastic : Three "submit" button, each sets the value of a particular attribute differently


Good evening,

I'd like to set up a form with a single field (name), where the user inputs their name, and then they select one of three buttons.

Each of these buttons should simultaneously set a particular attribute value, and submit the form.

A contrived example ("xxxx" is a button):

Name : _________
"Good" "Sad" "Tired"

This would save the user's name, and then yes/no/maybe to the "users_feeling" attribute. I don't want to have a radio box for the user feeling attribute and then a separate submit button.

Any help you could provide would be appreciated!!


Solution

  • There are two ways how to do this in general.

    IMHO the better one is to simply add the attribute you want to set as a hidden field, and then write some javascript to set it to perhaps some data attribute on the button. Something like this:

    $('.my_form button').click ->
      $('#my_hidden_field').val ($ @).data 'attribute-name'
      $('.my_form')[0].submit()
    

    The other is that each submit button will pass its value as a parameter when you submit the form. You can detect this in your rails controller like any other value. So if you have this HTML:

    <input type=submit name=feeling value=Good />
    <input type=submit name=feeling value=Sad />
    <input type=submit name=feeling value=Tired />
    

    Then in your controller params[:feeling] should hold the value of the button clicked. Why I don't particularly like this solution is that the value string is also what is displayed to the user which couples your controller with your view rather nastily. If in the future you'd like to localize your app this will likely bite you.