AJAX and REST: rendering partials

I have an Items resource and each Item has an attribute ‘starred’. The
items/index page shows a list of items, each one is in its own partial
and has an image of a star (star_off.gif) next to it. When the star is
clicked, an AJAX PUT request is made to the Update action. The starred
attribute is updated and a the items partial is replaced so that
star_on.gif is shown. So far so good, the code is below:


<% if item.starred?%> <%= link_to_remote image_tag('star_on.gif',:class => 'star'), :url => item_url(item), :with => "'item[starred]=false'", :method => :put
<% else %>
  <%= link_to_remote image_tag('star_off.gif',:class => 'star'),
                     :url => item_url(item),
                     :with => "'item[starred]=true'",
                     :method => :put
<%= link_to item.name, item_path(item) %>


def update
@item = Item.find(params[:id])
respond_to do |format|
if @item.update_attributes(params[:item])
format.js {render :update do |page|
page.replace “item_#{@item.id}”, :partial =>
‘shared/item’, :locals => {:item => @item}

The problem comes when I am working on the show.html.erb page. This
page shows the details of the item. I want show the star on this page
too and have the same functionality, i.e. the stars state changes when
the image is clicked. However, the controller is coded to render the
shared/item partial when a javascript request is received, this is not
what I want on the show page. The _item.html.erb is for the index page,
I do not want to render this when the request comes from the show page.

Am I approaching the AJAX calls in the correct way here? The partial
that needs to be rendered after the update action is dependent on where
the AJAX call is made from. How is this done, or am I doing something
completely wrong?

Hi Tim,

Tim C. wrote:

The partial that needs to be rendered after the update action
is dependent on where the AJAX call is made from.

The easy way to handle this is simply to pass a param, probably via a
hidden_field_tag, that tells you from which partial the method was
There’s nothing unRESTful about this. The only downside is that it’ll
you to do your rendering in the controller rather than just letting
render the default view. Nothing really wrong with that either though.
method will look something like…

def update
respond_to do |format|
format.js {
if params[:called_from] == ‘show’
render_update do |page|
page.replace_html …
elsif params[:called_from] == ‘list’
render_update do |page|
page.replace_html … something else
#might want to do some error trapping here


Thanks for the help, I have implemented it in the way you suggested.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs