有多个控制器操作接收 startDate 作为参数并将其传递给相关模型以获取数据。基于用户属性,必须对该参数应用验证规则。验证不仅会失败,而且会分配特定于该用户属性的默认值。
startDate 上所需的修改在所有操作中都是通用的,应应用于所有情况。所以,我认为这个逻辑不应该在每个模型上重复。相反,控制器的 before_action 过滤器,像filtered_params 听起来是正确的地方。
before_action :filtered_params
def filtered_params
params.require(:query).permit(:start_date)
user = User.instance
if(user.type == 'student') {} # startDate should be Greater than or equal to 12-03-2018. modify params.startDate with the logic
elsif(user.type == 'professor') {} // startDate should be Greater than equal to 01-01-2018
else {} // do nothing
end
end
上述方法有效,但我不想陷入 if else 循环。有没有更好的方法来做到这一点?
也许你可以这样做:
before_action :filtered_params
def filtered_params
@filtered_params ||= get_filtered_params
end
def get_filtered_params
# not sure about this user assignment, but let's go with it...
user = User.instance
begin
"ParamsFilter::#{user.type.camelize}Service".constantize.call params
rescue NameError => e
# I'm guessing at the default behavior here. You would need to
# modify to meet your requirements.
return params.require(:query).permit(:start_date)
end
end
那么你需要类似的东西:
app
|- services
| |- params_filter
| | |- service_base.rb
| | |- student_service.rb
| | |- professor_service.rb
| |- service_base.rb
服务可能看起来像
class ParamsFilter::StudentService < ParamsFilter::ServiceBase
MIN_START_DATE = '12-03-2018'
#======================================================================
# Instance Methods
#======================================================================
def call
# In this case, given how ServiceBase is defined, the params will
# be received as `args`, so you'll need to work with the `args`
# variable, which will contain `params`.
# You could do stuff unique to `student`:
student_stuff
# and then do some common stuff by calling `super`.
super
end
private
def student_stuff
end
end
哪里ParamsFilter::ServiceBase
可能看起来像:
class ParamsFilter::ServiceBase < ServiceBase
#======================================================================
# Instance Methods
#======================================================================
def call
args[:start_date] = self.class::MIN_START_DATE unless start_date_okay?
end
private
def start_date_okay?
args[:start_date] >= self.class::MIN_START_DATE
end
end
哪里service_base.rb
可能看起来像:
class ServiceBase
attr_accessor *%w(
args
).freeze
class << self
def call(args=nil)
new(args).call
end
end # Class Methods
#======================================================================
# Instance Methods
#======================================================================
def initialize(args)
@args = args
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句