【问题标题】:Rails 4 Strong Params ErrorRails 4强参数错误
【发布时间】:2013-09-29 04:17:45
【问题描述】:

我正在使用 rails 4。我有一个使用验证的模型,但不存储任何记录。它仅用于发送电子邮件的网络联系表单。

我正在尝试对这个控制器/模型使用强参数。目前,我的新操作出现 nomethoderror。有任何想法吗?我认为这与我的模型不是一个成熟的模型有关。?

精简代码以便于查看。

型号:

class Message
  include ActiveModel::Model
  include ActiveModel::ForbiddenAttributesProtection
end

控制器:

class MessagesController < ApplicationController
  def new
    @message = Message.new
  end

  private

    def project_params
      params.require(:message).permit(:name, :email, :content)
    end
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 strong-parameters


    【解决方案1】:

    您的project_params 需要重命名为message_params,因为您希望在MessagesController 而不是project 中允许消息。

    请尝试:

    class MessagesController < ApplicationController
      def new
        @message = Message.new
      end
    
      private
    
        def message_params
          params.require(:message).permit(:name, :email, :content)
        end
    end
    

    更新:

    此外,虽然您提到了“精简代码以便于查看”,但我要补充一点,您还需要为这些允许的属性定义 att_accessor,如下所示:

    class Message
      include ActiveModel::Model
      include ActiveModel::ForbiddenAttributesProtection
    
      attr_accessor :name, :email, :content
    end
    

    请参阅路易十四对此问题的回答:“Rails Model without a table

    【讨论】:

    • message_params 很好。我试图从项目脚手架复制一些代码。我不明白为什么我必须在 Rails 4 中添加 attr_accessor?运行脚手架,它不使用 attr_accessor,并且 params.require(model).permit(columns) 使用创建和更新操作运行。新操作在模型中只有 @project = Project.new 并且没有 attr_accessor。
    • @KeilMiller,您必须在模板文件中访问这些属性,例如new.html.erb,这是 NoMethodError 的来源。强参数直接替换了在 Rails4 之前用于批​​量分配的attr_accessible。我们使用attr_accessor,一种ruby 方法来定义属性的getter 和setter。请查看attr_accessorattr_accessible 之间的区别。
    • 我想我现在明白了。非常感谢您的清晰解释。这个question/answer 也有助于区分 attr_accessible 和 attr_accessor。
    猜你喜欢
    • 2013-07-30
    • 2013-12-07
    • 1970-01-01
    • 2013-07-11
    • 2015-04-19
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多