2014-04-28 62 views
1

Rails noob,Rails使用請求參數進行自定義驗證?

我想寫一個自定義驗證,但我依賴於來自發布請求的參數。這個例子與我所具有的相似 - 在這個後期模型中,我想驗證用戶是否已經發布了一些主題,但要做到這一點,我必須從帖子請求中獲得主題ID:

class Post < ActiveRecord::Base 
... 
    validate :user_already_posted, on: :create 
    def user_already_posted 
     topic=Topic.where(id: params[:topicId]).first 
     //some code that runs on topic users and makes sure the user hasn't posted there 

但是,我瞭解到params不是全局的,模型不能訪問它(我最後使用laravel的地方並非如此,所以這對我來說很困惑)。 自定義驗證不適合我需要的嗎?是否需要查看過濾器或讓控制器運行自己的驗證功能?

回答

0

我想你在這裏有一點設計問題。您正在創建驗證程序post,但驗證本身不是關於post實例。我的意思是,模型驗證器必須使用內置的默認驗證器ActiveRecord或創建自定義驗證器來評估所有post屬性,就像您通過self訪問屬性一樣。
我相信class method接收所有的參數和檢查post創造了條件更加清晰:在控制器上的模型

類方法

def self.user_already_posted(topic_id, user_id) 
    # Do your thing 
end 

使用

can_create = Post.user_already_posted(params[:topic_id], params[:user_id) 
+0

是的,這是有道理的。 –

1

你可以這樣做:

validates_uniqueness_of :user, scope: :topic_id 

可能不會恰好是你需要的,但問題是,你可以在範圍內驗證。 您也可以傳遞一個數組來驗證多個參數。

validates_uniqueness_of :user, scope: [:topic_id, :post_id]