42

I am trying to get some Javascript working in my Rails app.

I want to have my index page allow me to edit individual items on the index page, and then reload the index page upon edit.

My index.html.erb page looks like:

<div id="index">
<%= render 'index' %>
</div>

In my index.js.erb I have:

$('#index').html("<%=j render 'index' %>");

and in my holders_controller:

def edit
  holder = Holder.find(params[:id])
 end

def update
  @holder = Holder.find(params[:id])
  if @holder.update_attributes(params[:holder])
    format.html { redirect_to holders_path } #, flash[:success] = "holder updated")
    ## ^---Line 28 in error
    format.js
  else
    render 'edit'
  end
end

When I load the index page it is fine. As soon as click the edit button and it submits the form, I get the following:

enter image description here

But if I go back and refresh the index page, the edits are saved. What am I doing wrong?

Promise Preston
  • 24,334
  • 12
  • 145
  • 143
Noah Clark
  • 8,101
  • 14
  • 74
  • 116

1 Answers1

129

You forgot to write responds_to block:

def update
  @holder = Holder.find(params[:id])
  if @holder.update_attributes(params[:holder])
    respond_to do |format|
      format.html { redirect_to holders_path } #, flash[:success] = "holder updated")
      format.js
    end
  else
    render 'edit'
  end
end

But I am suspicious about your index.html.erb, I don't think that will really work the way you think.

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Matzi
  • 13,770
  • 4
  • 33
  • 50
  • 1
    @Matzi I had to use `responds_to do |format|` to get it to work. – Noah Clark Jun 26 '12 at 14:55
  • @Matzi, Also. It works, kinda. Since it redraws the page, it's probably not any better than just reloading the page. The only way would be if I could figure out how to redraw just that one item. In any case, I now understand how to do it in the future. – Noah Clark Jun 26 '12 at 14:57
  • Thanks, NoahClark, Matzi, and all. – Matthew Brown Feb 15 '13 at 04:29
  • Question: why does some code have respond_to and other code just have redirect_to and omit the respond_to do |format| block? Seems to work in both cases, most of the time...I imagine there is a default if no respond_to is present? – Danny May 23 '13 at 18:45
  • The `respond_to` is just a selector to let you answer based on the format of the request. If you leave it out completely it will return the default rendered view on any format type. In the question the problem was with the usage of `format.html` without `respond_to`. – Matzi May 23 '13 at 20:28
  • This error's description is too short to understand where is wrong.:( – Albert.Qing Mar 30 '16 at 10:01
  • you're a time saver! – Roshan Oct 09 '19 at 11:07