Rails 3.1 Ajax question

2020-07-18 10:14发布

问题:

I have a scaffold called post which has a title and a description. On my layout I have a link to create a new post that has :remote => true. How would I make it when I click on that remote link to change the content of a div so that I can create a new post?

回答1:

Let's suppose the action you will use is called new. You should create a file called new.js.erb into views/posts that will be rendered when you post remotely your form. That file must include the javascript that places the new post into the div you want to fill. As an example, it could contain

# new.js.erb
$('div#container').html("<p><%= escape_javascript(@post.title) %></p>").append("<p><%= escape_javascript(@post.content) %></p>"); 

The javascript will be executed immediately after the ajax post is finished and the new post is created. Remember the following: - You have to include jQuery - You have to specify in posts_controller the ability to render .js format, something like

# posts_controller.erb
def create
    @post = Post.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to(@post, :notice => 'Post created via non AJAX.') }
        format.js # the actual ajax call
      else
        format.html { render :action => "new" }
      end
    end
end