ActiveModel::ForbiddenAttributesError
错误通常出现在 Ruby on Rails 应用程序中,当尝试使用未授权的属性创建或更新 Active Record 对象时。这个错误是 Rails 的安全特性之一,旨在防止恶意用户通过表单提交不应该被允许的字段。
在 Rails 中,模型(Model)负责业务逻辑和数据验证,而控制器(Controller)则处理用户输入并调用模型来执行操作。ActiveModel::ForbiddenAttributesError
错误通常发生在控制器尝试使用未经授权的属性创建或更新模型实例时。
这个错误通常与以下几种情况相关:
这个错误常见于以下场景:
假设你在 FormulairesController#create
方法中遇到了这个错误,可以通过以下步骤解决:
class FormulairesController < ApplicationController
def create
@formulaire = Formulaire.new(formulaire_params)
if @formulaire.save
redirect_to @formulaire, notice: 'Formulaire was successfully created.'
else
render :new
end
end
private
def formulaire_params
params.require(:formulaire).permit(:title, :content)
end
end
在这个例子中,formulaire_params
方法定义了哪些字段可以被接受。只有 :title
和 :content
字段会被允许传递给 Formulaire.new
方法。
确保你的表单只包含允许的字段。例如:
<%= form_with(model: @formulaire, local: true) do |form| %>
<% if @formulaire.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@formulaire.errors.count, "error") %> prohibited this formulaire from being saved:</h2>
<ul>
<% @formulaire.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :title %>
<%= form.text_field :title %>
</div>
<div class="field">
<%= form.label :content %>
<%= form.text_area :content %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
formulaire_params
方法,Rails 会默认拒绝所有参数,导致这个错误。params.require(:formulaire)
中的 :formulaire
与表单中的模型名称一致。通过上述方法,可以有效解决 ActiveModel::ForbiddenAttributesError
错误,并确保应用程序的安全性和代码的清晰性。
领取专属 10元无门槛券
手把手带您无忧上云