我正在努力将Rails 3v项目升级到5v。一切似乎都有效,但我收到了这个错误:
ContactsController #create中的ActiveModel :: ForbiddenAttributesError
::加载ActiveModel ForbiddenAttributesError
@contact = Contact.new params [:contact]
这是我的模特:
class Contact < ApplicationRecord
belongs_to :contactable, :polymorphic => true
attribute :contact
validates :email, :presence => true
validates :name, :presence => true
validates :body, :presence => true
validates :email, email: true, allow_blank: true
scope :are_read, -> { where("state = ? ","read") }
scope :are_unread, -> { where("state = ?","unread") }
state_machine :state, :initial => :unread do
event :reading do
transition :unread => :read
end
end
end
and
这是我的控制器:
# -*- encoding : utf-8 -*-
class ContactsController < ApplicationController
def new
@contact = Contact.new
if params[:product].present?
@contact.contactable = Product.find params[:product]
end
if params[:rental].present?
@contact.contactable = Rental.find params[:rental]
end
end
def create
# @user = User.new(user_params)
@contact = Contact.new params[:contact]
if @contact.save
UserMailer.contact_notification(@contact).deliver
redirect_to thanks_contact_path
else
render :new
end
end
def thanks
end
end
答案 0 :(得分:3)
尝试以下操作,在private
controller
方法
private
def contact_params
params.require(:contact).permit(:name, :email, :body)
end
像这样改变
def create
@contact = Contact.new(contact_params)
....
end
而不是
@contact = Contact.new params[:contact]
答案 1 :(得分:1)
Rails 4以后你不能直接使用params来进行质量分配。
您需要使用Strong Params
将参数列入白名单。
@contact = Contact.new params[:contact]
使用
def create
@contact = Contact.new(contact_params)
...
end
private
def contact_params
params.require(:contact).permit(:contact, :params, :attributes_here) # <= Change this
end