How can I call `update_attribute` for a list item in rails then actually update the html using jquery? -
i want users able mark 1 or more items index view "active" or "inactive" using link. text link should state aware - might default "mark active" if corresponding attribute false or null, , "mark inactive" if true. once user clicks link , attribute updated in controller, link-text should update based on new state.
i way off here, small sample of code 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 respond .js here end end ...
update.js.erb #how identify element update? $('#item[13456]').html("state aware text link_to")
view - item in @items = item.name = link_to "mark active", item_path(item), :method => :put, :remote => true. :id => "item[#{item.id}]"
i happy read apis, blogs, tutorials, etc. can't seem hands/mind around task. or guidance appreciated!
this rough starting idea you.
i'll start easy stuff; view:
= link_to @item.active == true ? "yes" : "no", make_active_path(@item), :class => 'item'
then if click on item target jquery , ajax:
this bad ass function work other things throw @ top of javascript file. :
jquery.fn.submitwithajax = function() { this.live("click", function() { $.ajax({type: "get", url: $(this).attr("href"), datatype: "script"}); return false; }); };
then inside rest of jquery code write :
$(".item").submitwithajax();
the ajax request fired off 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 |format| format.js { render :action => "update", :layout => false } end end
then make update.js.erb :
$("#item_#{@item.id}").replacewith("#{ escape_javascript(render :partial => 'controller/item_view', :locals => {:item_view => @item}) }");
but means need have each item inside of own partial inside of parent view :
= render :partial => 'item_view', :collection => @items
inside of file called _item_view.html.haml
write:
%div{:id => "item_#{item_view.id}"} %div{:id => "post_#{post_view.id}"}
don't forget make route in routes.rb method.
Comments
Post a Comment