如何动态更改path_to()?

时间:2010-05-08 04:39:34

标签: ruby-on-rails send

我目前有三种方法可以合并为一种方法:

  def send_email(contact,email)

  end

  def make_call(contact, call)
    return link_to "Call", new_contact_call_path(:contact => contact, :call => call, :status => 'called')
  end

  def make_letter(contact, letter)
    return link_to "Letter", new_contact_letter_path(:contact => contact, :letter => letter, :status => 'mailed')
  end

我想将三者合并为一个,这样我就可以将模型作为其中一个参数传递,它仍然可以正确地创建path_to。我试图用以下方法做到这一点,但卡住了:

  def do_event(contact, call_or_email_or_letter)
    model_name = call_or_email_or_letter.class.name.tableize.singularize
   link_to "#{model_name.camelize}", new_contact_#{model_name}_path(contact, call_or_email_or_letter)" 
  end

感谢这里的答案,我尝试了以下内容,让我更接近:

link_to( "#{model_name.camelize}", send("new_contact_#{model_name}_path", 
                                        :contact => contact, 
                                        :status => "done",
                                        :model_name => model_name) )

但我似乎无法弄清楚当#{model_name}是一个:属性时如何通过#{model_name},然后发送model_name的值,而不是字符串,而是引用该对象。

我让这个工作: - 给Kadada点数,因为他让我朝着正确的方向前进:)

  def do_event(contact, call_or_email_or_letter) 
    model_name = call_or_email_or_letter.class.name.tableize.singularize 
    link_to( "#{model_name.camelize}", send("new_contact_#{model_name}_path", 
                                            :contact => contact, 
                                            :status => 'done',
                                            :"#{model_name}" => call_or_email_or_letter ) )                                       
  end 

1 个答案:

答案 0 :(得分:2)

试试这个:

def do_event(contact, call_or_email_or_letter)
  model_name = call_or_email_or_letter.class.name.tableize.singularize
  link_to( "#{model_name.camelize}", send("new_contact_#{model_name}_path", 
                 contact, call_or_email_or_letter) )
end