How do I create a polymorphic model with a collection_select?

Posted by muxe on Stack Overflow See other posts from Stack Overflow or by muxe
Published on 2010-05-11T16:37:55Z Indexed on 2010/05/11 17:54 UTC
Read the original article Hit count: 162

This are my models:

class Speaker < ActiveRecord::Base
  belongs_to :session, :foreign_key => :session_id, :class_name => :Session
  belongs_to :speakable, :polymorphic => true
end  

class Session < ActiveRecord::Base
  has_many :speakers
  accepts_nested_attributes_for :speakers
end

class Person < ActiveRecord::Base
  has_many :speakers, :as => :speakable
end       

class Company < ActiveRecord::Base
  has_many :speakers, :as => :speakable
end  

What I want to do now is something like this: app/views/sessions/edit.html.erb

  <% f.fields_for :speakers do |sf| %>
    <p>
      <%= sf.label :speaker %><br />
      <%= sf.collection_select :speakable, Company.all + Person.all, :id, :full_name %>  
    </p>
  <% end %>

But it is not working because of the polymorphic assignment. How do I approach this problem?

EDIT: The Error is:

undefined method `base_class' for String:Class

with params being:

"speaker"=>{"speakable"=>"1063885469", "session_id"=>"1007692731"}

The value passed to speakable is the id of the Speaker/Company. Yes, this is the value I specified the collection_select to return, but how can I manage to supply both values (speakable_id and speakable_type) ?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about polymorphic-associations