【问题标题】:Updating Rails 4 code to Rails 4.2 code将 Rails 4 代码更新为 Rails 4.2 代码
【发布时间】:2015-04-09 12:45:15
【问题描述】:

我正在阅读 Apress “Beginning Rails 4, 3rd edition”一书。本书通过逐步构建博客应用程序向您介绍 Rails。我已经完成了一半,收到以下错误消息:

ActiveModel::ForbiddenAttributesError in CommentsController#create

我已将此追溯到我的 cmets_controller.rb 文件,该文件如下所示:

class CommentsController < ApplicationController
  before_filter :load_article

  def create
    @comment = @article.comments.new(params[:comment])
    if @comment.save
      redirect_to @article, :notice => 'Thanks for your comment'
    else
      redirect_to @article, :alert => 'Unable to add comment'
    end
  end

  def destroy
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to @article, :notice => 'Comment deleted'
  end

  private
    def load_article
      @article = Article.find(params[:article_id])
    end
end

具体来说,问题似乎是由第 5 行引起的:

@comment = @article.comments.new(params[:comment])

根据我收集到的信息,问题似乎在于我正在阅读的这本书是为早期版本的 Rails 编写的。我使用的是 Rails 4.2.0,看来我需要使用不同的语法。我需要进行哪些更改才能使我的代码正常工作?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-4.2


    【解决方案1】:

    您需要一个在控制器中称为 comment_params 的私有方法(约定俗成,您可以称其为任何名称)

    控制器:

    def create
      @comment = @article.comments.new(comment_params)
      if @comment.save
        redirect_to @article, :notice => 'Thanks for your comment'
      else
        redirect_to @article, :alert => 'Unable to add comment'
      end
    end
    
    private
    
    def comment_params
      params.require(:comment).permit!
    end
    

    它叫做 strong_parameters,是一个 gem,所以你可以在 github 上用 google 找到它

    params.require(:comment).permit! 将允许任何事情,您可能希望通过传递属性 params.require(:comment).permit(:name, :message) 来限制它 - 假设您具有名称和消息属性。

    如果您有更新方法中的comment_params 方法调用,您需要替换params[:comment]

    【讨论】:

      【解决方案2】:

      您需要在创建模型对象之前执行此操作。 Rails 必须先清理参数,然后才能将其放入其中。

      comment_params = params.require(:comments).permit(:attribute1, :attribute2)
      @comment = @article.comments.new(comment_params)
      

      【讨论】:

        【解决方案3】:

        load_article方法下添加如下方法:

        def comment_params
          params.require(:comment).permit( ... )
        end
        

        并将三个点替换为您需要允许的属性。

        然后在你的创建函数中你可以写

        @comment = @article.comments.new(comment_params)
        

        您可能需要在 update 函数中执行类似的操作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多