1

我如何在 rails 2 中获取带有主机名的完整 url

我正在寻找的是url_for在模型类中使用并在开头附加当前主机 url

例如

从模型类调用它

url_for(:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title)

这应该返回

http://www.hostname.com/wiki/show/projectname/wikipageid

4

1 回答 1

1

在您的模型中包含以下模块

  include ActionView::Helpers::UrlHelper
  include ActionView::Helpers
  include ActionDispatch::Routing
  include Rails.application.routes.url_helpers

然后您可以创建一个名为generete_url 的函数并将url_for 调用到该函数中

 class User
   include Mongoid::Document
   include ActionView::Helpers::UrlHelper
   include ActionView::Helpers
   include ActionDispatch::Routing
   include Rails.application.routes.url_helpers


   def generate_url

     url_for(:host => "abcd",:action => 'new', :controller => 'users', :only_path => false, :protocol => 'https') 
   end   
 end

这是我的用户模型,当我这样做时,我得到了输出

u = User.new
u.generate_url 
# => https://abcd/users/new 
于 2012-08-14T12:37:40.527 回答