如何在自己的控制器中以format.js进行渲染

时间:2015-11-06 00:48:25

标签: ruby-on-rails

我正在做一个从show到新页面的ajax。但是在帖子被保存之后,它需要呈现/posts/new页面。我收到错误说法语错误。我的代码如下:

posts_controller:

def create
    @post = Post.new(post_params)
     respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
    format.json { render :new, status: :created, location: @post }

   # format.js { :file => "/posts/new" } *not working
   # format.js { :location => "new_post" } *not working

  else
    format.html { render :new }
    format.json { render json: @post.errors, status: :unprocessable_entity }
  end
end
end
edi:抱歉有错字。已添加end,评论已更改。我还不知道如何渲染"/posts/new"

2 个答案:

答案 0 :(得分:1)

你错过了结束块,Dimension d = getSize(); if(x < 0 || x > d.width){xspeed =- xspeed;} if(y < 0 || y > d.height){yspeed =- yspeed;} 不是ruby评论标记,Ruby使用//。所以:

#

关于功能:

这会重定向:

def create
  @post = Post.new(post_params)
  respond_to do |format|
    if @post.save
      format.html { redirect_to @post, notice: 'Post was successfully created.' }
      format.json { render :new, status: :created, location: @post }
      # format.js { :file => "/posts/new" } *not working
      # format.js { :location => "new_post" } *not working
    else
      format.html { render :new }
      format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
end

这会呈现包含整个布局的页面:

format.html { redirect_to @post, notice: 'Post was successfully created.' }

这只呈现页面内容(这可能是你想要的ajax):

format.html { render :new }

所以要在成功保存后呈现新页面:

format.html { render :new, layout: false }

答案 1 :(得分:0)

看起来你错过了end,对齐语句有助于更容易识别。

def create
 @post = Post.new(post_params)
   respond_to do |format|
     if @post.save
       format.html { redirect_to @post, notice: 'Post was successfully created.' }
       format.json { render :new, status: :created, location: @post }

       # format.js { :file => "/posts/new" } *not working
       # format.js { :location => "new_post" } *not working
     else
       format.html { render :new }
       format.json { render json: @post.errors, status: :unprocessable_entity }
     end
   end
end

编辑:是的,因为dsokurenko指出//无效Ruby评论错过了,更新。