2016-08-15 67 views
3

我遇到了問題,我正在嘗試使用我的#new -action上的表單向平常添加地址。
我在做什麼目前,是嵌套參數,與多態​​一對一

class Person < ActiveRecord::Base 
    has_one :address, :as => :owner 

    accepts_nested_attributes_for :address 
end 

class Address < ActiveRecord::Base 
    belongs_to :owner, :polymorphic => true 
end 

在我的形式,我使用form_for @person do |f| - 那麼的形式,然後f.fields_for :address do |af|和領域,使用af.text_field

我的控制器動作:

def create 
    person = Person.new(person_params) 

    if person.valid? 
    person.save 
    redirect_to edit_content_person_path(@current_work_context, person) 
    else 
    @person = person 
    render 'new' 
    end 
end 

def person_params 
    params.require(:person).permit(:name, :address => [:line_one, :line_two, :zipcode, :city]) 
end 

當我提交我的形式,與這些參數:

{"utf8"=>"✓", 
"authenticity_token"=>"blablabla==", 
"person"=>{"name"=>"mr man", 
"address"=>{"line_one"=>"test address 15", 
"line_two"=>"", 
"zipcode"=>"2600", 
"city"=>"Glostrup"}}, 
"locale"=>"da", 
"context_id"=>"9"} 

然而,我得到異常:ActiveRecord::AssociationTypeMismatch

Address(#70198415678880) expected, got ActionController::Parameters(#70198414055220) 

我似乎無法找出原因。

編輯 - 我的看法,簡化:

<%= form_for @person do |f| %> 

    <%= f.text_field :name %> 

    <%= f.fields_for :address do |af| %> 
    <%= af.label :address %> 
    <%= af.text_field :line_one, :placeholder => "Address 1" %> 
    <%= af.text_field :line_two, :placeholder => "Address 2" %> 

    <%= af.label :zipcode %> 
    <%= af.text_field :zipcode, :class => "form-control" %> 

    <%= af.label :city %> 
    <%= af.text_field :city, :class => "form-control" %> 

    <% end %> 

<% end %> 
+0

這將有助於瞭解在哪一行,你收到此錯誤。 – 2016-08-15 09:44:13

+0

噢 - 對。 對'Person.new'行 –

+0

很陌生。 'accepted_nested_attributes_for' with'f.fields_for:address' should be transform you like ...''person「=> {」name「=>」mr man「, 」address_attributes「=> {」line_one「=> 「測試地址15」 –

回答

1

讓改掉一兩件事。請與該行並重新啓動服務器

# config/initializers/inflections.rb 

ActiveSupport::Inflector.inflections do |inflect|' 
    inflect.irregular 'address', 'addresses' 
end 

編輯

# after we discussing more about the problem in chat we found the solution. 
# The object 'Person' not initialize correctly to f.fields_for :address 

# view 

<% f.object.build_address if f.object.address.blank? %> #add this line 
<%= f.fields_for :address do |af| %> 
+0

不幸的是,沒有成功。我得到同樣的例外。 –

+0

唯一的區別是你的實現比我的名字是類型'addresses.rb',我的has_many是這樣'has_many:addresses,class_name:'Addresses',如::addressable' –

+0

我有'address.rb'和一個一對一的關係.. –