How do I dynamically change the path_to()?

2019-06-11 22:54发布

问题:

I currently have three methods which I want to collapse into one:

  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

I want to collapse the three into one so that I can just pass the Model as one of the parameters and it will still correctly create the path_to. I am trying to do this with the following, but stuck:

  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

Thanks to the answers here, I have tried the following, which gets me closer:

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

But I can't seem to figure out how to past the #{model_name} when it is an :attribute and then send the value of model_name, not as a string, but referring the object.

I got this to work: -- giving points to Kadada because he got me in the right direction :)

  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:

Try this:

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