Rails 5保存多态关联父表单

时间:2017-06-19 09:11:49

标签: ruby-on-rails ruby forms polymorphism

这让我发疯!我想在Rails 5中保存父对象表单中的多态对象,我找不到方法。

我有一个模型联系人,它可以有多个多态地址,但我找不到在父创建表单上保存地址的方法。

这些是我的模特:

class Contact < ApplicationRecord
  has_many :addresses, as: :addressable
  accepts_nested_attributes_for :addresses
end

class Address < ApplicationRecord
  belongs_to :addressable, polymorphic: true
end

我想让用户在创建新联系人时只创建一个地址。我在ContactsController#new

上构建地址
class ContactsController < ApplicationController

  def new
    @contact = Contact.new
    @contact.addresses.build
  end

  def create
    @contact = Contact.new(contact_params)

    if @contact.save
      redirect_to contacts_path
    else
      render :action => 'new'
    end
  end

  private

  def contact_params
     params.require(:contact).permit(
       :name, :email, :mobile,
       addresses_attributes: [:country, :state, :city, :street, :code])
  end
end

创建一个嵌套表单:

<%= form_for @contact do |f| %>
  <%= f.text_field :name %>
  <%= f.text_field :mobile %>
  <%= f.text_field :email %>

  <%= f.fields_for :addresses do |a| %>
    <%= a.text_field :country %>
    <%= a.text_field :state %>
    <%= a.text_field :city %>
    <%= a.text_field :postal_code %>
    <%= a.text_field :street %>
  <% end %>

  <%= f.submit 'Create Contact' %>
<% end %>

它不起作用。当我保存表单时,我收到一个错误:

#<ActiveModel::Errors:0x007faac415a768 @base=#<Contact id: nil, 
 name: "John Doe", email: "john@doe.com", mobile: "666666666", 
 created_at: nil, updated_at: nil>, 
@messages={:"addresses.addressable"=>["must exist"]}, 
@details={:"addresses.addressable"=>[{:error=>:blank}]}>

任何人都知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

这&#34;解决&#34;这个问题,但这样做很可怕:

def create
  @contact = Contact.new(contact_params)
  @contact.addresses.last.addressable = @contact

  if @contact.save
    redirect_to contacts_path
  else
    render :action => 'new'
  end
end