htmlruby-on-railsrubydatabaseruby-datamapper

Ruby on Rails radio button selection to database


Im currently working on a form where the user are able to choose between 1-5 radio button alternatives and then upload what they choose to a database.

I'm currently using different name on each radio button and then check which param posted is equal to "on". But since the relationship and the params are described with name I cant get the relationship between the buttons to work (if one button is active the other/s are not active)

So how can I tell which radio button is active if I can't use different names and check for params?

      <div class="form-group">
        <div class="col-lg-10">
        <p style="font-size: 16px">
          <input type="radio" id="option1" name="option1" />
          <label for="option1"><%= @poll.option1 %></label></p>
         </div>
      </div>

      <div class="form-group">
        <div class="col-lg-10">
          <p style="font-size: 16px">
            <input type="radio" id="option2" name="option2" />
            <label for="option2"><%= @poll.option2 %></label></p>
        </div>
      </div>

And this is how I check which on is active, but how can I check if a radio button is active if they dont use different names/params? I'm using Sinatra and Datamapper, SQLite for database management.

if params["option1"] == "on"
  Vote.create(vote: "option1", ip: ip_adress, poll_id: poll.id)
  redirect urlstring
end
if params["option2"] == "on"
  Vote.create(vote: "option2", ip: ip_adress, poll_id: poll.id)
  redirect urlstring
end

Solution

  • You need to specify values for the radio buttons to determine which was submitted - a radio button group will return the value of the selected button.

    In view:

    <input type="radio" name="options" value="1">Option 1</input>
    <input type="radio" name="options" value="2">Option 2</input>
    <input type="radio" name="options" value="3">Option 3</input>
    <input type="radio" name="options" value="4">Option 4</input>
    

    In controller:

    case params["options"].to_i
    when 1
      # Vote for 1
    when 2
      # Vote for 2
    ...
    end