0

I am using a button-group as a radio button to capture user input for a boolean field in my database. I have a wedding model with a boolean field :rsvp. The form below seems to capture the data. However, if I refresh the page, the button is no longer toggled with the user's choice. My question is, how to I get the button to persist the user's choice, even if the page is refreshed, or if the user logs out and logs in again?

Models

 class User < ActiveRecord::Base
  has_one :wedding
 end

 class Wedding < ActiveRecord::Base
  belongs_to :user
 end

Controllers

 class WeddingsController < ApplicationController

   def new
     @wedding = Wedding.new
   end

   def create
     @wedding = current_user.build_wedding(params[:wedding])
      if @wedding.save
       redirect_to root_path
     else
       render 'new'
     end
   end

 class StaticPagesController < ApplicationController
   def home
    @wedding = Wedding.new
   end

View:

home.html.erb

  <%= form_for(@wedding, :remote => true) do |f| %>
     <div class="btn-group-wrap">
          <div class="btn-group" data-toggle="buttons-radio">
             <%= f.button 'Yes', :class => "btn btn-large btn", :value => "1", :name => "wedding[rsvp]" %>
              <%= f.button 'No', :class => "btn btn-large btn", :value => "0", :name => "wedding[rsvp]" %>
          </div>
     </div>
  <% end %>
diasks2
  • 2,033
  • 2
  • 36
  • 61

2 Answers2

1

I should recommend you to use a radio input but hide the circle (some css will do the trick) and add the class of bootstrap over the input so you get the button looking.

Check it out this other post: How to make a radio button look like a toggle button

Community
  • 1
  • 1
Jorge Najera T
  • 1,511
  • 2
  • 20
  • 29
0

Here is how I ended up doing it (using Javascript). Not sure if it is the best way or not. I added an ID tag to each button and then toggled that button using javascript and a conditional that depends on the value in the my database.

 <div class="btn-group" data-toggle="buttons-radio">         
        <%= f.button :rsvp, :id => "rsvp_true", :class => "btn btn-large btn", :value => "1", :name => "wedding[rsvp]" %>
        <%= f.button :rsvp, :id => "rsvp_false", :class => "btn btn-large btn", :value => "0", :name => "wedding[rsvp]" %>      
 </div>

 <script>
   $(document).ready(function() {
  <% if current_user.wedding.rsvp == true %>
    $('#rsvp_true').button('toggle');
  <% else %>
    $('#rsvp_false').button('toggle');
  <% end %>
   });
 </script>
diasks2
  • 2,033
  • 2
  • 36
  • 61