如何动态更改path_to()?
我目前有三种方法,我想将其合并为一种:
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} :attribute,然后发送 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
Try this: