如何在Ruby on Rails中为.find动态分配模型?

Tim*_* T. 3 ruby-on-rails dynamic

我正在尝试创建单表继承.

但是,Controller必须能够知道要查找或创建的类.这些是基于另一个类.

例如,type = Letter的ContactEvent需要从名为Letter的相应模型中获取属性.

这是我试图做的事情,并在下面标出了一个障碍.

我需要能够动态调用EventClass的值,以便它可以是Letter.find(:conditions =>)或Calls.find(:conditions =>),具体取决于控制器所采用的类型.

  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'
Run Code Online (Sandbox Code Playgroud)

SNAG下面:

    @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
Run Code Online (Sandbox Code Playgroud)

nic*_*ick 12

这应该允许您动态调用模型,使用User模型的示例:

model = "user".capitalize.constantize
model.all
Run Code Online (Sandbox Code Playgroud)

用法示例:

model = params[:object_type].capitalize.constantize
if model.destroy_all(params[:object_id])
  render :json => { :success => true }
else
  render :nothing => true
end
Run Code Online (Sandbox Code Playgroud)


Chu*_*bas 6

@event_class = case @contact_event.type
  when 'letter' then Letter
  when 'email'  then Email
  when 'call'   then Call
end
Run Code Online (Sandbox Code Playgroud)

您必须分配类本身,而不是字符串.然后你可以打电话@event_class.find(whatever).有些事情需要注意:

支持单表继承,并由Rails自动处理.您可以从ContactEvent获得Letter,Email和Call继承.阅读Rails API的更多信息(单表继承部分)

您可以通过调用直接转换字符串@contact_event_type.classify.constantize(例如,将"调用"转换为"调用").

另外,尝试根据ruby约定(@event_type而不是@EventType)命名变量,并检查你对case语句的使用.

希望它有用:)