How do I dynamically change the path_to()?

久未见 提交于 2019-12-08 11:24:26

问题


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


来源:https://stackoverflow.com/questions/2792946/how-do-i-dynamically-change-the-path-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!