How to say this Ajax call in Rails3?

advertisements

I am struggling with this Ajax call from Rails 2:

   def add_task_link(name)
      link_to_function name do |page|
         page.insert_html :bottom, :tasks, :partial => 'task', :object => Task.new
      end
   end

How can I express this with Rails 3?

Thanks,


I think you might want link_to :remote => true instead. The link_to_function is meant to accept a string of javascript code that it puts in the onclick attribute. So instead of your helper method, use something like

<%= link_to 'My Link', new_task_path, :remote => true %>

Then in your new action, you need to add a .js respond to block.

def new
  @task = Task.new
  respond_to do |format|
    format.html
    format.js { render :layout => false } # add this line
  end
end

Then create a file under app/views/tasks called new.js.erb, and add:

$('body').append('<%= escape_javascript(render :partial => "form", :locals => { :task => @task }) %>');

Provided the partial form is setup (which you can use anyways for your new.html.erb and edit.html.erb files) that should work just fine. Took some examples from this example repository: https://github.com/nu7hatch/rails3-ujs-example/blob/master/ I have to admit, I don't do a lot of link_to remote coding examples in Rails. Most ajax calls I do are using JSON responses. So I write the js code under the asset pipeline.