How can I call `update_attribute` for a list item in rails then actually update the html using jquery?
I want my users to be able to mark one or more items from an index view as "Active" or "Inactive" using a link. The text for the link should be state aware - so it might default to "Mark as Active" if the corresponding attribute was false or null, and "Mark as Inactive" if true. Once the user clicks the link and the attribute is updated in the controller, the link-text should update based on the new state.
I am WAY off here, but this is a small sample of the code I have been trying...
CONTROLLER
...
respond_to :html, :js
...
def update
@item = Item.find(params[:id])
if @item.update_attributes(params[:item])
#Not sure of how to respond to .js here
end
end
...
update.js.开发者_JAVA技巧erb
#how do I identify which element to update?
$('#item[13456]').html("State aware text for link_to")
VIEW
- for item in @items
= item.name
= link_to "Mark as Active", item_path(item), :method => :put, :remote => true. :id => "item[#{item.id}]"
I am happy to read any APIs, blogs, tutorials, etc. I just can't seem to get my hands/mind around this task. Any help or guidance is greatly appreciated!
This is a rough starting idea for you.
I'll start with the easy stuff; the view:
= link_to @item.active == true ? "yes" : "no", make_active_path(@item), :class => 'item'
Then if they click on the item we target it with jQuery and AJAX:
This bad ass function will work for you for other things too so just throw this at the top of your javascript file. :
jQuery.fn.submitWithAjax = function() {
this.live("click", function() {
$.ajax({type: "GET", url: $(this).attr("href"), dataType: "script"});
return false;
});
};
Then inside with the rest of your jQuery code write this :
$(".item").submitWithAjax();
The AJAX request is fired off to your controller :
def make_active
@item = Item.find(params[:id])
if @item.active == true
@item.update_attribute("active","false")
else
@item.update_attribute("active","true")
end
respond_to do |format|
format.js { render :action => "update", :layout => false }
end
end
Then make update.js.erb say :
$("#item_#{@item.id}").replaceWith("#{ escape_javascript(render :partial => 'controller/item_view', :locals => {:item_view => @item}) }");
But that also means that you need to have each item inside of its own partial inside of a parent view like so :
= render :partial => 'item_view', :collection => @items
Inside of a file called _item_view.html.haml
write:
%div{:id => "item_#{item_view.id}"}
%div{:id => "post_#{post_view.id}"}
Don't forget to make a route in your routes.rb for this method.
精彩评论