views:

21

answers:

1

I'm using a simple ajax toggle partial in a view, to allow a user to toggle a message as read vs. unread. When I toggle I get a failure.

MessagesController#show could not find MessageCopy without an ID.
Application trace: messages_controller.rb:21 in 'show' (first line of the action)

show.html.erb
  <%= render :partial => "read_unread_buttons" %>

# read_unread_buttons partial
  <div id="read_buttons" class="ajaxButtonText">
  <% if @message.read == true %>
    <%= link_to "Mark Unread",
    {:url => {:action => "read_unread_toggle", :id => @message.id},
     :update => {:success => "read_buttons", :failure => "Error"}}, 
    {:class=>"messageButton", :id => "markUnread"}, :remote => true %>
  <% else %>
    <%= link_to "Mark as Read",
    {:url => {:action => "read_unread_toggle", :id => @message.id},
     :update => {:success => "read_buttons", :failure => "Error"}},
     {:class=>"messageButton", :id=>"markUnread"}, :remote => true %>     
  <% end %>
  </div>

# messages controller
  def show
    @message = current_user.received_messages.find(params[:id])
    @message.read = true
    @message.save(:validate => false)
    render :layout => "messages"
  end

  def read_unread_toggle
    @message = current_user.received_messages.find(params[:id])
    @message.read = [email protected]
    @message.save(:validate => false)
    render :partial => "read_unread_buttons", :locals => {:message => @message, :id => params[:id] }, :layout => false
  end
A: 

First, I'd suggest using the generated path url method to generate the href, you'll see this in the example below.

Second, I assume your routes.rb looks something like this:

resources :messages do
  member do
    put 'read_unread_toggle'
  end
end

Then your read_unread_buttons partial should look like this

# read_unread_buttons partial
  <div id="read_buttons" class="ajaxButtonText">
  <% if @message.read == true %>
    <%= link_to "Mark Unread", read_unread_toggle_message_path(@message),
     { :update => { :success => "read_buttons", :failure => "Error" } }, 
     { :class => "messageButton", :id => "markUnread" }, { :method => :put, :remote => true } %>
  <% else %>
    <%= link_to "Mark as Read", read_unread_toggle_message_path(@message),
     { :update => { :success => "read_buttons", :failure => "Error" } },
     { :class => "messageButton", :id=>"markUnread" }, { :method => :put, :remote => true } %>     
  <% end %>
  </div>

Specifically, you forgot to specify the method the HTTP method the link should use.

Patrick Klingemann
sorry, I edited this a few times. There might be a few mistakes in there. First I'd try it with your url generation scheme until it works, then use the read_unread_toggle_message_path method. Also, you should try to be consistent with your spacing and indentation, it'll make your code much more readable. Good luck.
Patrick Klingemann