【问题标题】:How to support multiparameter attributes in a rails form object?如何在 Rails 表单对象中支持多参数属性?
【发布时间】:2017-10-20 15:06:44
【问题描述】:

我有一个使用此处定义的模式的表单对象:https://forum.upcase.com/t/form-objects/2267

class RegistrationForm
  include ActiveModel::Model

  attr_accessor :first_name, :last_name, :date_of_birth
  ...
end

与该示例不同,我的表单中的一个基础模型有一个日期字段。该日期字段以简单形式呈现为多参数属性,并通过以下方式提交给控制器:

"user"=>
  {"first_name"=>"Hanna",
   "last_name"=>"Macias",
   "date_of_birth(1i)"=>"2016",
   "date_of_birth(2i)"=>"2",
   "date_of_birth(3i)"=>"26",
...

但是,我在控制器上的 #create 操作中收到来自 RegistrationForm.new(registration_params)unknown attribute 'date_of_birth(1i)' for RegistrationForm. 错误:

def create
  @registration = RegistrationForm.new(registration_params)
  if @registration.save
    redirect_to root_path
  else
    render 'new'
  end
end

private

def registration_params
  params.require(:registration).permit!
end

我尝试为:date_of_birth_1i, :date_of_birth_2i, :date_of_birth_3i 等定义额外的attr_accessors,但这并没有解决问题。

如何正确处理多参数属性?

【问题讨论】:

  • 也许这可以帮助你,guides.rubyonrails.org/form_helpers.html#nested-forms 以及这个 api 页面 edgeapi.rubyonrails.org/classes/ActionController/… 我相信你的参数应该类似于 params.require(:user).permit(:first_name)。最好在这个post 请求上设置binding.pry,然后在控制台中检查params hash 以及如何设置方法registration_params 以包括first_name。也许你需要params.require("user").permit("first_name"),在控制台中测试一下,看看它是否能检索到你的输入

标签: ruby-on-rails forms activerecord multiparameter


【解决方案1】:

我需要include ActiveRecord::AttributeAssignmentActiveModel::Model,这样就解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 2014-06-26
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多