1

Currently trying to switch a poll's is_live attribute in the database through a button click in the view. Here's the form and click, which doesn't send the polls data in params.

  - current_user.polls.each do |poll| 
    %tr#poll.id
      %td
        / Need to add (poll) as it needs the ID to match to the route.
        =link_to "#{poll.title}", poll_path(poll)
      %td
        =link_to "Edit", edit_poll_path(poll)
      %td
        - if poll.is_live
          = link_to "Stop"
          / , post, :method=>:toggle_live, :remote=>true, :class => 'btn btn-danger stop-poll'
        - else
          **= link_to "Start", polls_toggle_live_path(poll), :method => :post, :remote => true, :locals => poll, :class=> 'btn btn-success btn-small start-poll'**  

Which links to this action in the PollsController

  def toggle_live
    binding.pry

    @poll = Poll.find(params[:id])

    respond_to do |format|
      **format.js {@poll.toggle_live}**
    end

  end

Which links to this method in the Poll model I've tested this in rails c and it does switch the toggle the boolean value

  def toggle_live
    if self.is_live
      self.is_live = false
    else
      self.is_live = true
    end
  end

How can I use all these things to switch the boolean with a click event?
Currently I'm getting this error from the server log:

Started POST "/polls/toggle_live.30" for 127.0.0.1 at 2013-06-09 12:15:02 -0400
Processing by PollsController#toggle_live as 
Completed 404 Not Found in 2447731ms
Keith Johnson
  • 730
  • 2
  • 9
  • 19

1 Answers1

2

The reason for the 404 is that your method should be put and not post. Along the way, may I suggest in the model:

def toggle_live
  self.is_live = !is_live
end

And in the controller something like:

def toggle_live
  @poll = Poll.find params[:id]
  # do something to verify the user has the right to toggle this poll
  @poll.toggle_live
end

Since the request is made by remote: true, you know that Rails will automatically render your JS template, so the respond_to is superfluous.

davidfurber
  • 5,274
  • 1
  • 20
  • 11