How do I toggle link states when clicked with AJAX and Rails?
In one of my index actions I want to display a link that says either "activate" or "de-activate", depending on whether the record is active or not.
When the user clicks on an "activate" or "de-activate" link for a particular record, a call should be made to my update action that updates the record accordingly, and if the link said "activate" it should be changed to "de-activate" and vice versa.
How might I achieve this? I've looked at link_to_remote
, but I have no idea how I'm going to toggle th开发者_如何学Ce text for the link.
It's ok to use link_to_remote, you then have to respond to js format in your controller and send js code to be executed with page update:
update_page do |page|
page.replace_html 'link_id', "<a href='#'>OtherState</a>"
page.visual_effect :highlight, 'link_id' # you can highlight the item to give more feedback to the user
end
In my view I put this:
<% for account in @accounts %>
<tr id="<%= "update[#{account.id}]" %>">
<%= render :partial => "account", :object => account %>
</tr>
<% end %>
In my update action I put this:
def update
@account = Account.find(params[:id])
respond_to do |format|
if @account.update_attributes(params[:account])
format.html do redirect_to(@account)
flash[:notice] = 'Account was successfully updated.'
end
format.xml { head :ok }
format.js { render :partial => 'account' }
else
format.html { render :action => "edit" }
format.xml { render :xml => @account.errors, :status => :unprocessable_entity }
end
end
end
And in my partial I put this:
<td><%=h account.email %></td>
<td><%=h account.password %></td>
<td><%=h account.get_status %></td>
<td><%=h account.network.name %></td>
<td>
<%=
link_to_remote(
# name
account.get_status == :active ? 'De-activate' : 'Activate',
# options = {}
{
:url =>
{
:controller => "accounts",
:action => :update,
:id => account.id,
:account => { :status => account.get_status == :active ? account.find_status(:inactive) : account.find_status(:active) }
},
:method => :put,
:update => "update[#{account.id}]",
},
{
:with => "'account[status]=' + $('account['status']).value"
}
)
%>
</td>
<td><%= link_to 'Edit', edit_account_path(account) %></td>
<td><%= link_to 'Destroy', account, :confirm => 'Are you sure?', :method => :delete %></td>
The docs aren't very clear on sending parameters from link_to_remote
to your actions. The parameters you want to send to your update actions, you would put in the options
hash of link_to_remote
, and from this my records are successfully updated when the link is clicked.
Also, for the actual 'toggling' of the text of the link, a ternary condition in the name
parameter of link_to_remote
is what did the trick.
精彩评论