How do I dynamically assign the Model for a .find in Ruby on Rails?
Posted
by Angela
on Stack Overflow
See other posts from Stack Overflow
or by Angela
Published on 2010-05-27T03:42:51Z
Indexed on
2010/05/27
3:51 UTC
Read the original article
Hit count: 233
ruby-on-rails
|dynamic
I am trying to create a Single Table Inheritance.
However, the Controller must be able to know which class to find or create. These are based on another class.
For example, ContactEvent with type = Letter needs to grab attributes from a corresponding Model called Letter.
Here's what I've tried to do and hit a snag, labelled below.
I need to be able to dynamically call assign a value of EventClass so that it can be Letter.find(:conditions =>) or Calls.find(:conditions =>) depending on which type the controller is acting on.
def new
@contact_event = ContactEvent.new
@contact_event.type = params[:event_type] # can be letter, call, postcard, email
@contact_event.event_id = params[:event_id] # that ID to the corresponding Model
@contact_event.contact_id = params[:contact]
@EventClass = case
when @contact_event.type == 'letter' then 'Letter'
when @contact_event.type == 'call' then 'Call'
when @contact_event.type == 'email' then 'Email'
SNAG BELOW:
@event = @EventClass.find(@contact_letter.letter_id) #how do I make @EventClass actually the Class?SNAG
# substitution of variables into the body of the contact_event
@event.body.gsub!("{FirstName}", @contact.first_name)
@event.body.gsub!("{Company}", @contact.company_name)
@evebt.body.gsub!("{Colleagues}", @colleagues.to_sentence)
@contact_event.body = @event.body
@contact_event.status = "sent"
end
© Stack Overflow or respective owner