Updating attributes from check_box

156 views Asked by At

I'm using nested models in my first Ruby on Rails app and now I've run into a problem. I have a Survey model that has_many :questions which in turn belongs_to :survey and the model Question has_many :answers. My Answer model then belongs_to :question.

Now I want to update a boolean attribute :guess within my :answers controller. To this end I've created a new action :quiz_guess which looks like this:

      def quiz_guess
         Answer.update(params[:id], guess: false)
             puts("Guess saved")
         redirect_to(:action => 'show', :id => @survey.next, :survey_id => @survey.id)  
      end

my view looks like this:

    <%= form_tag quiz_guess_questions_path, :method => :put do %>   
       <% for question in @survey.questions do %>
         <li><%= h question.content %></li>
            <% for answer in question.answers do %>
                <li><%= h answer.content %>
                   <%= form_for :guess do |f| %>
                     <%= f.check_box(:guess, :method => :put) %>
                   <% end %>
                </li>
            <% end %>
       <% end %>
    <% end %>

Obviously I've read the documentation, as well as this blog post, but I don't understand how to implement it in my controller and view.

With this code I'm not able to update the correct :guess attribute but rather I update a different one (with a different :id). Can anybody shed some light as to what I do wrong?

1

There are 1 answers

0
ljnissen On BEST ANSWER

I ended up looking at this Railscast where Ryan Bates shows how to update multiple attributes with fields_for. This is my new view:

   <%= form_tag quiz_guess_questions_path, :method => :put do %>
     <% for question in @survey.questions do %>
        <li><%= question.content %></li>
         <% for answer in question.answers do %>
          <li>
            <%= fields_for "answers[]", answer do |f| %>
              <%= answer.content %>  
              <%= f.check_box :guess %>    
            <% end %>
          </li>
         <% end %>
     <% end %>
    <%= submit_tag "Guess" %>
   <% end %>

and my new controller:

  def quiz_guess
     Answer.update(params[:answers].keys, params[:answers].values)
     flash[:notice] = "Guess saved successfully."
     redirect_to questions_url
  end