2017-05-04 63 views
0

我正在制作一个博客式应用程序,并且正在编辑时更新帖子。无法在Ruby on Rails上更新帖子

我使用的部分称为_post_form编辑帖子:从我的帖子控制器

<%= form_for(@post) do |f| %> 
<%= render 'shared/error_messages', object: f.object %> 
<div class="field"> 
<%= f.text_area :content, placeholder: "Compose new post..." %> 
</div> 
<div id="post_button"> 
<%= f.submit "Post", class: "btn btn-primary" %> 
</div> 
<% end %> 

相关代码:

class PostsController < ApplicationController 
before_action :find_note, only: [:show, :edit, :update] 

def update 
    redirect_to @post 
end 

def find_note 
    @post = Post.find(params[:id]) 
end 

当我点击“发布”按钮,将我重定向到正确的但是它不会使用我输入到表单中的新文本实际更新它。我觉得我缺少一些基本的东西,但我不确定它是什么。

任何帮助表示赞赏!

回答

1

您没有更新控制器中的任何内容,只是将用户重定向到post视图。

首先获得新的post值:

def post_params 
    params.require(:post).permit(:content) 
    end 

,然后更新它重定向之前:全部放在一起

def update 
    @post.update(post_params) 
    redirect_to @post 
end 

,控制器应该是这个样子:

class PostsController < ApplicationController 
    before_action :find_note, only: [:show, :edit, :update] 

    def update 
    @post.update(post_params) 
    redirect_to @post 
    end 

    private 

    def post_params 
    params.require(:post).permit(:content) 
    end 

    def find_note 
    @post = Post.find(params[:id]) 
    end 
end 
+0

感谢这个伟大的答案,我现在明白了很多! – Andrew

1

您缺少模型update致电PostsController#update这是您的帖子记录未更新的原因。在PostsController#update行动重定向

def update 
    @post.update(post_params) ## <- add this 
    redirect_to @post 
end 

注意之前更新后的记录:假设你使用Rails版本> = 4,并在白名单属性post_params(强参数)。