在rails 2模型中获取完整的链接URL

时间:2012-08-14 11:14:02

标签: ruby-on-rails ruby-on-rails-2

如何在rails 2中使用主机名获取完整的URL

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

e.g。

从模型类中调用它

  

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

这应该返回

  

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

1 个答案:

答案 0 :(得分: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