2012-02-01 48 views
1

我試圖按照軌道中的一條基本規則DRY(不要重複自己) 我有以下型號在視圖中使用型號限制

class Micropost < ActiveRecord::Base 
    attr_accessible :content  
    belongs_to :user 
    validates :content, :presence => true, :length => { :maximum => 140 } 
    validates :user_id, :presence => true 
    default_scope :order => 'microposts.created_at DESC' 
end 

和形式,我限制與文本區域Java腳本

f.text_area :content, 
    :onKeyDown =>"textCounter(micropost_content,counter,140)", 
    :onKeyUP =>"textCounter(micropost_content,counter,140)" 

我想在java腳本函數中使用驗證的最大值。

我該怎麼做?

回答

2

最簡單的解決辦法是提取神奇的數字140爲常數,那麼這兩個驗證中使用它:

class Micropost < ActiveRecord::Base 

    MAX_CONTENT_LENGTH = 140 

    validates :content, 
      :presence => true, 
      :length => { :maximum => MAX_CONTENT_LENGTH } 

end 

和視圖裏面:

f.text_area :content, 
      :onKeyDown => "textCounter(micropost_content, counter ,#{Micropost::MAX_CONTENT_LENGTH})", 
      :onKeyUP => "textCounter(micropost_content, counter, #{Micropost::MAX_CONTENT_LENGTH})" 
+0

感謝,像變魔術一樣 – ekrako 2012-02-01 14:02:12