2012-09-13 66 views
1

post.rbRuby on Rails的支持驗證,如果條件

@allowed_post_types = [ 
    'type1', 
    'type2', 
    'type3', 
    'type4' 
    ] 

    #validate post type 
    validates :post_type, :presence => true, :inclusion=> { :in => @allowed_post_types }, :if => :valid_post_type? 



    def valid_post_type? 
    self.post_type != 'type5' 
    end 

我怎樣才能使validates :post_type行代碼每當:post_type成的Type5

試過以上,但它似乎沒有工作

回答

2

嘗試:

validates :post_type, 
      :presence => true, 
      :inclusion=> { :in => @allowed_post_types }, 
      :if => lambda { |a| a[:post_type] != "type5" }