简体   繁体   English

Rails 5保存多态关联父窗体

[英]Rails 5 Save polymorphic association parent form

This is driving me crazy!!! 这真让我抓狂!!! I want to save in Rails 5 a polymorphic object within the parent object form, and I can't find a way. 我想在Rails 5中将父对象表单中的多态对象保存起来,但找不到方法。

I have a model Contact and it can have multiple polymorphic addresses, but I can't find a way to save an address on the parent creation form. 我有一个模型Contact,它可以有多个多态地址,但是我找不到在父创建表单上保存地址的方法。

These are my models: 这些是我的模型:

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

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

I would like to let the user to create just one address when he creates a new contact. 我想让用户在创建新联系人时仅创建一个地址。 I am building addresses on ContactsController#new 我在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

And create a nested form: 并创建一个嵌套表单:

<%= 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 %>

It does not work. 这是行不通的。 When I save the form I get an error: 保存表单时出现错误:

#<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}]}>

Anyone has an idea what I am doing wrong? 有人知道我在做什么错吗?

This "solves" the problem, but it is terrible to do it this way: 这样可以“解决”问题,但是这样做很糟糕:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM