我有一个实例,在这个实例中,我将对一个资源进行某些验证,而不是另一个资源,其中两个资源映射到同一个模型。
具体地说,我有一个链接到竞赛的导出模型,我构建了该竞赛中所有用户的导出。所以自然会有一个验证,以确保有一个附加的竞争。但是,客户也希望能够在给定的时间构建所有的用户导出,并让它像竞争对手的导出一样工作。
我计划为此使用两个单独的资源(路由、控制器),但验证只在每个资源级别上有意义。
有人对wrt最佳实践有什么想法吗?
发布于 2017-02-13 19:50:43
老实说,不是。您最好的解决方案是将导出变量的职责拆分到特定的类中,这些类在模型上执行您想要的行为。例如,Psuedo代码,只是在这里猜测实现--可能需要抓取:
class CompetitionExports
self.abstract_class: true # order just include the relevent ActiveRecord modules
MODEL = Export
def initialize(id)
@competition_export_id = id
end
def all
return [] unless validate
MODEL.where(id: competition_exports_id).joins(:users) #can pluck/ select what you want here
end
private
attr_reader :competition_export_id
def validate
return true if MODEL.where(id: competiton_export_id).has_competition?
self.errors.add(:competition, 'does not exist')
false
end
end
class UserExports
self.abstract_class: true # order just include the relevent ActiveRecord modules
MODEL = Export
def initialize(id)
@user_export_id = id
end
def all_at(date)
return [] unless validate(date)
MODEL.where(id: user_exports_id).joins(:users) #can pluck/ select what you want here
end
private
attr_reader :user_export_id
def validate(date)
return true if MODEL.where(id: user_export_id, date: date).present?
self.errors.add(:user, "no users at #{date}")
false
end
end因此,在这里,我有两个资源,它们检查导出模型以了解它们自己的特定行为,而不会实际干扰模型本身。这将业务逻辑保持在模型级别本身,而不会将其与所有内容混合在一起。
在控制器中,您可以只实例化当时需要的类。因此,对于所有竞赛用户:
export = CompetitionExports.new(params[:id])
export.all 或特定日期的用户
export = UserExports.new(params[:id])
export.all_at(params[:date])在处理结果之前,两者都将运行其特定的验证。
发布于 2017-02-13 18:49:16
您可以在rails中设置自定义验证或条件验证。
请参考下面的链接
http://www.justinweiss.com/articles/a-lightweight-way-to-handle-different-validation-situations/
希望能对你有所帮助。
https://stackoverflow.com/questions/42201139
复制相似问题