开发者

Rails Polymorphic Assignment

I've had success creating dependent polymorphic associations using accepts_nested_attributes_for, but now I would like to assign an already existing polymorph. I'm getting the error:

undefined method `id' for {"id"=>"4"}:ActiveSupport::HashWithIndifferentAccess

Models:

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

class Company < ActiveRecord::Base
  has_one :address, :as => :addressable
end

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

View:

<%= form_for @company do |f| %>
  <p>
    <%= f.label :company_name %><br />
    <%= f.text_field :company_name %>
  </p>

  <%= f.fields_for :address do |f| %>
    <div class="field">
      <%= f.collection_select :id, Addres开发者_StackOverflow中文版s.all, :id, :description, {:prompt => "-Select Address"} %>
    </div>
  <% end %>

The resulting params hash is:

"company"=>{"company_name"=>"myCompanyName", "address"=>{"id"=>"4"}}

Which looks reasonable to me. What am I doing wrong?


Change f.fields_for :address do |f| to f.fields_for :address do |d| and f.collection_select to d.collection_select if it isn't mistype

<%= form_for @company do |f| %>
  <p>
    <%= f.label :company_name %><br />
    <%= f.text_field :company_name %>
  </p>

  <%= f.fields_for :address do |d| %>
    <div class="field">
      <%= d.collection_select :id, Address.all, :id, :description, {:prompt => "-Select Address"} %>
    </div>
  <% end %>
<% end %>


You should be able to add accepts_nested_attributes_for :address to Person and Company, which produces a params hash like this:

{"company"=>{"company_name"=>"myCompanyName", "address_attributes"=>{"id"=>"4"}}}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜