[英]Rails 4 ForbiddenAttributesError
我有以下表格:
= semantic_form_for @contact, :url => club_contact_path(id: @club.id), :html => {:novalidate => false, :id => 'contact_club_form'} do |f|
.sm-12.xl-5
= f.input :club_id, :as => :hidden, :input_html => { :value => @club.id }
= f.input :firstname, :required => true
= f.input :lastname, :required => true
= f.input :email, :required => true
= f.input :telephone, :as => :phone, :required => false
= f.input :question, :required => true, :as => :text, :input_html => {:rows => 5, :cols => 40}
= f.action :submit, :button_html => {:class => 'btn btn-aqua', :value => 'Submit'}
下面,我已經將contact_params
方法添加到控制器中。 出現此錯誤,並告訴我我有一個Rails::ForbiddenAttributesError
,但是我似乎無法弄清楚原因。
def contact_params
params.require(:contact).permit(:firstname, :lastname, :email, :telephone, :question, :club_id)
end
我的模型如下:
class Contact < ActiveRecord::Base
belongs_to :club
validates_presence_of :firstname, :lastname, :email, :question, :telephone, :club_id
end
編輯:添加的動作
def contact_club
@contact = params[:contact]
if Contact.create(@contact)
byebug
ContactMailer.send_contact_mail_to_club(@contact)
render :nothing => true
end
end
您應該在創建操作中傳遞允許的參數,而不是直接參數。 因此,在您的創建調用中,嘗試將@contact
更改為contact_params
。
在當前代碼中,您沒有傳遞正確的參數。 因此,請嘗試如下更改代碼。
def contact_club
@contact = params[:contact]
if Contact.create(contact_params)
byebug
ContactMailer.send_contact_mail_to_club(@contact)
render :nothing => true
end
end
contact_params方法將您的參數包裝在Rails現在期望的創建或保存新對象的類中。 現在,您正在直接訪問它,如果您使用強大的參數,您將無法再訪問它。 您想要將contact_params傳遞給Contact.new或Contact.create方法。
另外,我對您的設置@contact = params [:contact]感到困惑,我認為您正在嘗試獲取Contact模型的實例,然后將其傳遞給郵件程序。 那是對的嗎? 如果是這樣,則以下代碼段應更接近您要查找的內容。
def contact_club
@contact = Contact.new(contact_params)
if @contact.save
byebug
ContactMailer.send_contact_mail_to_club(@contact)
render :nothing => true
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.