Ruby on rails 如何更改对象';Rails中所有方法的s值?
我有一个项目,其中他们的实体或类称为研究性学习,有一个字段Ruby on rails 如何更改对象';Rails中所有方法的s值?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个项目,其中他们的实体或类称为研究性学习,有一个字段title和mobile title。现在我使用gem来检测访问者的设备(桌面、手机等)。现在,我想要的是,对于台式机,它应该始终返回'title',对于所有其他设备,它应该返回'mobilettitle' 我如何才能做到这一点,从而不需要在我返回研究的任何地方更改应用程序中的所有方法?有没有解决方案,如果我在一个地方改变它,它应该反映在所有方法中 编辑:因为这有很多反对票,我想澄清一下我需要什么。这是我的班级: clas
title
和mobile title
。现在我使用gem来检测访问者的设备(桌面、手机等)。现在,我想要的是,对于台式机,它应该始终返回'title',对于所有其他设备,它应该返回'mobilettitle'
我如何才能做到这一点,从而不需要在我返回研究的任何地方更改应用程序中的所有方法?有没有解决方案,如果我在一个地方改变它,它应该反映在所有方法中
编辑:因为这有很多反对票,我想澄清一下我需要什么。这是我的班级:
class ResearchStudy < ActiveRecord::Base
attr_accessible \
:title,
:mobile_title
....
end
class ResearchStudy
这是我的控制器,方法是获取所有研究和过滤器,以获得如下设备类型:
class Api::ResearchStudiesController < ApplicationController
before_filter :check_agent
def check_agent
@ua = AgentOrange::UserAgent.new(request.user_agent)
end
def get_all_studies
.....
answer_status_for_user() // before returning studies i modify the title according to device type
render json: { studies: @studies.to_json(:include => [:research_paper]) }
end
def answer_status_for_user
if @ua.is_mobile?
@studies.each do |study|
study.title = study.mobile_title
end
end
end
class Api::ResearchStudiesController[:研究论文])
终止
为用户定义应答状态
如果@ua.u是移动的?
@学习。每个人都要学习|
study.title=study.mobile\u title
终止
终止
终止
现在的问题是,在
获取所有研究中
我有各种各样的方法在应用,因为这是一个相当大的应用,所以有时候这项研究不会像上面那样做出反应(@studies
)。我想要的是,每当我们加载研究时,我想要应用一些更改(可能在构造函数中或其他地方),这些更改返回mobile\u title
,而不是title
,类似于ResearchStudy
类本身或任何其他解决方案,但我不确定如何在模型中覆盖这种情况下的属性读取器
class YourModel < ActiveRecord::Base
def title
if device_is_mobile?
"Title for Mobile"
else
"Default title"
end
end
end
your_object = YourModel.last
your_object.title # it will give you title depending upon which device being used.
classyourmodel
由于您正在修改模型的默认读卡器,因此可以在web应用程序以及Rails控制台中访问该读卡器。请向我们展示您已经尝试过的内容。我已对问题进行了编辑,以提供一个清晰的视图,请查看和指导