I have a page on my site that lets users respond to invites by either accepting or declining them.
Their response is stored in the database as the boolean ‘accepted’, and is used to apply the classes ‘selected’ or ‘not_selected’ (selected makes the text orange) to the ‘attending’ div or the ‘not attending’ div.
<% @going, @not_going = invite.accepted ? ['selected','not_selected'] : ['not_selected','selected'] %>
<%= link_to(outing_invite_accept_path( { :outing_id => invite.outing_id, :invite_id => invite.user_id } )) do %>
<div class="attending_div <%= @going %>">
attending
</div>
<%end %>
<%= link_to(outing_invite_decline_path( { :outing_id => invite.outing_id, :invite_id => invite.user_id } )) do %>
<div class="attending_div <%= @not_going %>">
not attending</div>
</div>
<% end %>
When either div is clicked, it’s diverted to the appropriate controller actions:
def invite_accept
@outing = Outing.find(params[:outing_id])
@invite = OutingGuest.find_by_outing_id_and_user_id(params[:outing_id], params[:invite_id])
@invite.update_attribute(:accepted, true)
redirect_to({:action => "index"})
end
def invite_decline
@outing = Outing.find(params[:outing_id])
@invite = OutingGuest.find_by_outing_id_and_user_id(params[:outing_id], params[:invite_id])
@invite.update_attribute(:accepted, false)
redirect_to({:action => "index"})
end
And as right now, this code works just fine. But it requires the index page be refreshed for it to take effect.
I know it’s possible to update the page without a refresh using a jQuery ajax call attached to a listener on the appropriate div, but I have no idea what such a call would look like, or where to start, really…
You want to use rail’s link_to
:remote => true.See http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
For dealing with callbacks you can bind to certain events that will trigger. For example:
This page is also a pretty good write up: http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/