小编Sir*_*lot的帖子

Rails 5中具有多态关联的嵌套属性

我创建了一个Address具有多态关联模型,我想救它,虽然客户端模型嵌套的属性,但我得到Address addressable must exist@client.errors.

楷模:

class Client < ApplicationRecord
  has_one :address, as: :addressable, dependent: :destroy
  accepts_nested_attributes_for :address, :allow_destroy => true
end

class Address < ApplicationRecord
  belongs_to :addressable, polymorphic: true
end
Run Code Online (Sandbox Code Playgroud)

控制器:

class ClientsController < ApplicationController

  def new
    @client = Client.new
    @client.create_address
  end

  def create
    @client = Client.new(client_params)

    if @client.save
      ...
    else
      ...
    end
  end

  private
  def client_params
    params.require(:client).permit(:first_name ,:last_name, :company, address_attributes: [:line1, :line2, :line3, :city, :state_province, :postal_code, :country])
  end    
end
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails

4
推荐指数
3
解决办法
2931
查看次数

标签 统计

ruby-on-rails ×1