我正在将我的应用程序从用户空间的子目录迁移到子域(即,domain.com/~user to user.domain.com)。我目前在user类中有一个方法来获取每个用户的"home“URL:
class User
def home_url
"~#{self.username}"
# How I'd like to do it for subdomains:
#"http://#{self.username}.#{SubdomainFu.host_without_subdomain(request.host)}"
end
end我想为子域更新这一点,但不将域硬编码到方法中。正如您所看到的,我正在使用subdomain-fu插件,它提供了一些我可以用来完成此操作的方法,但它们需要访问request,而这对于模型是不可用的。
我知道让request在模型中可用被认为是不好的形式,所以我想避免这样做,但我不确定是否有好的方法来做到这一点。我想我可以在每次初始化模型时传递域,但我不认为这是一个好的解决方案,因为我必须记住在每次初始化类时这样做,这经常发生。
发布于 2010-01-13 06:37:04
虽然莫尔夫的答案很好,但它并没有解决我的具体问题,因为在某些情况下,其他模型需要调用User#home_url,因此我必须更新许多方法才能传递该域。
取而代之的是,我从他的最后一段中获得了灵感,并在我的应用程序的配置类中添加了一个base_domain变量,这是在ApplicationController的before_filter中设置的变量
module App
class << self
attr_accessor :base_domain
end
end
class ApplicationController < ActionController::Base
before_filter :set_base_domain
def set_base_domain
App.base_domain = SubdomainFu.host_without_subdomain(request.host)
end
end因此,当我需要获取模型中的域时,我可以只使用App.base_domain。
发布于 2010-01-13 01:38:35
模型不应该知道这个请求,你是对的。我会这样做:
# app/models/user.rb
class User
def home_url(domain)
"http://#{username}.#{domain}"
end
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# ...
def domain
SubdomainFu.host_without_subdomain(request.host)
end
# Make domain available to all views too
helper_method :domain
end
# where you need it (controller or view)
user.home_url(domain)如果有一个规范的用户主页网址,我会做一个可配置的默认域(例如YourApp.domain),如果你不带参数调用User#home_url,你就可以使用它。这允许您在概念上不存在“当前域”的地方构建主页URL。
https://stackoverflow.com/questions/2050938
复制相似问题