加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 多态关联和嵌套属性:: error =>:blank

发布时间:2020-12-17 03:33:00 所属栏目:百科 来源:网络整理
导读:我想保存一个深层嵌套的表单.有三种不同的模型:应用程序,申请人和地址.地址是多态的,因为应用程序和申请人都可以拥有它们.这些是我发送的参数: {"application"={ "loan_type"="purchase","loan_amount"=2500000,"borrower_attributes"={ "first_name"="Tes
我想保存一个深层嵌套的表单.有三种不同的模型:应用程序,申请人和地址.地址是多态的,因为应用程序和申请人都可以拥有它们.这些是我发送的参数:

{"application"=>{
    "loan_type"=>"purchase","loan_amount"=>2500000,"borrower_attributes"=>{
        "first_name"=>"Test","middle_name"=>"Test","last_name"=>"Test","birthdate"=>"01/01/1970","phone"=>"1231231234","email"=>"test@me.com","marital_status"=>"married","address_attributes"=>{
            "street_address"=>"xxxx Mission Street","city"=>"San Francisco","state"=>"CA","zip"=>xxxxx
        }
    }
}}

当我的请求中发送此消息时,我收到以下响应:

<Address id: nil,street_address: "1045 Mission Street",city: "San Francisco",state: "CA",zip: 94103,addressable_type: "Applicant",addressable_id: nil,created_at: nil,updated_at: nil>

并出现以下错误消息:

@messages={:"borrower.address.addressable"=>["must exist"]},@details={"borrower.address.addressable"=>[{:error=>:blank}]}

为什么我不能设置嵌套属性?我需要修复什么来使其工作?

这是我的相关文件:

application.rb中

class Application < ApplicationRecord
    before_save :assign_addresses!
    belongs_to :borrower,class_name: 'Applicant'
    belongs_to :coborrower,class_name: 'Applicant',optional: true
    has_one :address,as: :addressable

    accepts_nested_attributes_for :borrower
    accepts_nested_attributes_for :coborrower
    accepts_nested_attributes_for :address
end

Applicant.rb

class Applicant < ApplicationRecord
    has_many :applications
    has_one :address,as: :addressable
    validates_presence_of :first_name,:last_name,:phone,:email,:birthdate

    accepts_nested_attributes_for :address
end

Address.rb

class Address < ApplicationRecord
    belongs_to :addressable,polymorphic: true
    validates_presence_of :street_address,:city,:state,:zip
end

Applications_Controller.rb

class Api::ApplicationsController < ApplicationController

    ...

    def create
        @application = Application.new(application_params)

        if @application.save
            render json: @application,status: :created
        else
            render json: @application.errors,status: :unprocessable_entity
        end
    end

    private

    def application_params
        params.require(:application).permit(:loan_type,:loan_amount,borrower_attributes: [:first_name,:middle_name,:birthdate,:ssn,:marital_status,address_attributes: [:street_address,:zip]])
    end
end

解决方法

发现了这个问题.添加可选项后,一切正常:地址belongs_to是真的.这是一个新的Rails 5约定.我记得把它放在我的coborrower上,但不是那里.希望这有助于某人!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读