我应该将Rails中的控制器验证吗?
我有一个实例,我将对资源进行某些验证,但不是另一个,其中两个资源映射到相同的模型。我应该将Rails中的控制器验证吗?
具体来说,我有一个出口模型,它与一个竞赛相关联,并且我构建了该竞争中所有用户的出口。所以自然会有一个确认来确保有附加的竞争。但是,客户也希望能够在给定时间建立所有的用户出口,并使其像竞争出口一样工作。
我打算为该(路由,控制器)使用两个单独的资源,但验证只对每个资源级别有意义。
任何人有任何想法与最佳做法?
说实话,没有。您最好的解决方案是将出口变体的责任分成特定的类,以便在模型上执行所需的行为。例如伪代码,只是猜测在这里 - 实现,可能需要补炉:
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])
双方将通过其特定的验证处理结果之前运行。
您可以在rails中设置自定义验证或条件验证。
请参考以下链接
http://www.justinweiss.com/articles/a-lightweight-way-to-handle-different-validation-situations/
希望它帮助你。
差异实际上取决于创建导出的路线。 – unflores
Ohk那么,杰的回答在你的情况下更好 –
那么这两个描述的场景都是读取操作?验证确实只对写入操作有意义。 – leifg
我没有真的提到它,但验证是在创作。 – unflores