Rails 通用控制器中的 4 个强参数

Rails 4 Strong Parameters in generic controller

我有一个 "generic" 控制器负责管理所有 public 页面和操作

class PublicController < ApplicationController

  def index
  end

  def contact
    @contact = Contact.new(contact_params)
  end

  private

  def contact_params
    params.require(:contact).permit(:name, :email, :question, :subject)
  end

end

但是当我想访问 "contact us" link 时出现以下错误

param is missing or the value is empty: contact

是否可以在 "generic" 控制器内操作强参数,或者我应该只将它们用作名为 "Contact" 的控制器的一部分?

看起来错误是因为您在参数哈希中没有联系人参数。您想要更像以下内容:

def contact
  @contact = Contact.new
end

def send_contact
  @contact = Contact.new(contact_params)
end

private

def contact_params
  params.require(:contact).permit(:name, :email, :question, :subject)
end

def index
  @contact = Contact.new
end

def contact
  @contact = Contact.new(contact_params)   
end

private

def contact_params
  params.require(:contact).permit(:name, :email, :question, :subject)   
end

基本上你应该只调用 contact_params 你要发布到的操作。