Ruby on rails Can';我不知道它是否';从桌面或移动设备访问
我正在尝试为移动设备创建视图。我在Ruby on rails Can';我不知道它是否';从桌面或移动设备访问,ruby-on-rails,ruby,ruby-on-rails-4,mobile,view,Ruby On Rails,Ruby,Ruby On Rails 4,Mobile,View,我正在尝试为移动设备创建视图。我在ApplicationController中找到了其他人的代码: def check_for_mobile session[:mobile_override] = params[:mobile] if params[:mobile] prepare_for_mobile if mobile_device? end def prepare_for_mobile prepend_view_path Rails.root + 'app' + 'views_
ApplicationController
中找到了其他人的代码:
def check_for_mobile
session[:mobile_override] = params[:mobile] if params[:mobile]
prepare_for_mobile if mobile_device?
end
def prepare_for_mobile
prepend_view_path Rails.root + 'app' + 'views_mobile'
end
def mobile_device?
if session[:mobile_override]
session[:mobile_override] == "1"
session[:is_mobile] = nil
else
(request.user_agent =~ /(iPhone|iPod|Android|webOS|Mobile|iPad)/)
session[:is_mobile] = true
end
end
helper_method :mobile_device?
代码没有正确区分桌面和移动设备。当我运行此代码时,即使我在笔记本电脑上使用该应用程序,也会为移动设备生成视图。为什么呢
我不理解方法
check\u for\u mobile
的定义。params[:mobile]
从哪里来?params[:mobile]
在URL中设置。很可能在网站的页眉/页脚中有一个带有当前url的链接,并且附加了?mobile=1
。上面的代码将看到这一点,并切换到移动视图,而不考虑用户代理。Rails 4.1引入了一个新概念,它允许您为每种设备构建视图
# The request variant is a specialization of the request format,
# like :tablet, :phone, or :desktop.
# Example from Rails upgrade Guide:
before_filter do
request.variant = :tablet if request.user_agent =~ /iPad/
end
respond_to do |format|
format.html do |html|
html.tablet # renders app/views/projects/show.html+tablet.erb
html.phone { extra_setup; render ... }
end
end
对于Rails 4,您应该使用变体,即内置的对移动视图的支持。这里的细节:克里斯蒂安,谢谢你,我采用了这种方法,效果很好!请随意添加它作为答案,我会接受它。我添加了变体作为答案。