2017-02-13 38 views
0

我有一個實例,我將對資源進行某些驗證,但不是另一個,其中兩個資源映射到相同的模型。我應該將Rails中的控制器驗證嗎?

具體來說,我有一個出口模型,它與一個競賽相關聯,並且我構建了該競爭中所有用戶的出口。所以自然會有一個確認來確保有附加的競爭。但是,客戶也希望能夠在給定時間建立所有的用戶出口,並使其像競爭出口一樣工作。

我打算爲該(路由,控制器)使用兩個單獨的資源,但驗證只對每個資源級別有意義。

任何人有任何想法與最佳做法?

+0

那麼這兩個描述的場景都是讀取操作?驗證確實只對寫入操作有意義。 – leifg

+0

我沒有真的提到它,但驗證是在創作。 – unflores

回答

0

說實話,沒有。您最好的解決方案是將出口變體的責任分成特定的類,以便在模型上執行所需的行爲。例如僞代碼,只是猜測在這裏 - 實現,可能需要補爐:

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]) 

雙方將通過其特定的驗證處理結果之前運行。

+0

Hrm ...我認爲這是有道理的。您可能想要更改您的答案,以更好地反映我所做的修改。在另一個對象中包裝驗證似乎是有道理的。 – unflores

+0

我目前的答案仍然適合。無論如何,擁有獨立的資源路徑/控制器可能是最小的實現,但就驗證而言,無論如何都應該在模型級別將其抽象爲獨立類,而不是控制器。 理想情況下,所有控制器應該做的就是從視圖中獲取信息並將其傳遞給模型。它可以在模型層處理完信息之後做出如何響應的決定,但這確實是它應該做的。無論如何,希望這會有所幫助 - 只是一個關於如何分離邏輯的想法。高內聚,低耦合;) – JayJay

相關問題