How to dynamically assign a model to .find in Ruby on Rails?

I am trying to create single page inheritance.

However, the controller must know which class to look for or create. They are based on a different class.

For example, ContactEvent with type = Letter needs to capture attributes from the corresponding model named Letter.

Here is what I was trying to do and hit the miss marked below.

I need to be able to dynamically call the assignment of an EventClass value so that it can be Letter.find (: conditions =>) or Calls.find (: conditions =>) depending on what type of controller it is running 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
+3
source share
2 answers
@event_class = case @contact_event.type
  when 'letter' then Letter
  when 'email'  then Email
  when 'call'   then Call
end

, . @event_class.find(whatever). :

Rails. , ContactEvent. Rails API ( " " )

, @contact_event_type.classify.constantize (, "" Call).

, ruby ​​(@event_type @EventType) case.

, :)

+6

, :

model = "user".capitalize.constantize
model.all

:

model = params[:object_type].capitalize.constantize
if model.destroy_all(params[:object_id])
  render :json => { :success => true }
else
  render :nothing => true
end
+9

Source: https://habr.com/ru/post/1747292/


All Articles