【问题标题】:Ruby on Rails - Send contact form - Controller issuesRuby on Rails - 发送联系表 - 控制器问题
【发布时间】:2018-04-30 19:03:25
【问题描述】:

我的项目中有一个使用 Ruby on Rails(Ruby 2.4.0 和 Rails 5.2.0)的联系表。当我尝试发送表单时,出现以下错误:

Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)

ActiveModel::ForbiddenAttributesError - ActiveModel::ForbiddenAttributesError:
  app/controllers/contacts_controller.rb:7:in `create'

正如错误所说,我怀疑联系人控制器中存在错误。

contacts_controller.rb

class ContactsController < InheritedResources::Base

  def index 
  end

  def create
    @contact = Contact.new(params[:contact])
    if @contact.save
      ContactMailer.delay_for(10.seconds, retry: true).create(@contact)
      render nothing: true, status: 200
    else
      render nothing: true, status: 400
    end
  end

end

在一些旧版本的 Ruby 和 Rails 中,相同的代码可以正常工作。最近的版本有什么变化吗?有人可以帮助我吗?

谢谢。

【问题讨论】:

  • 您需要使用一种新的参数处理方法,称为强参数。您能否粘贴您的联系表单包含的确切字段?
  • Contact.new(params[:contact])
  • 您能否在“开发”模式下运行您的网站,这样您就可以获得堆栈跟踪而不是 500 错误?你的日志文件说什么?您的自动化测试对您的 create 操作有何看法?
  • 假设你有一个属性contact.is_admin (true/false)。您当前的代码将允许用户在没有保护的情况下设置此值 - 这可能不是您想要的!这就是为什么 rails 要求您通过 permit 定义可以设置哪些属性。

标签: ruby-on-rails ruby forms controller


【解决方案1】:

我认为你应该以某种方式改变它:

class ContactsController < InheritedResources::Base

  def index 
  end

  def create
    @contact = Contact.new(contact_params)
    if @contact.save
      ContactMailer.delay_for(10.seconds, retry: true).create(@contact)
      render nothing: true, status: 200
    else
      render nothing: true, status: 400
    end
  end

  private

  def contact_params
    params.require(:contact).permit(:name, :phone)
  end

end

您可以阅读更多详细信息herehere

【讨论】:

  • 这部分工作。我还需要在名为“create”的联系人中创建一个视图。现在工作正常。在一些旧版本的 Ruby on Rails 中,这不是必需的。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多