[英]Rails 5 Save polymorphic association parent form
这真让我抓狂!!! 我想在Rails 5中将父对象表单中的多态对象保存起来,但找不到方法。
我有一个模型Contact,它可以有多个多态地址,但是我找不到在父创建表单上保存地址的方法。
这些是我的模型:
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}]}>
有人知道我在做什么错吗?
这样可以“解决”问题,但是这样做很糟糕:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.