在视图中使用模型限制

时间:2012-02-01 13:09:50

标签: ruby-on-rails

我试图遵循其中一个rails基本规则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脚本限制textarea

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

我想使用java脚本函数中验证的最大值。

我该怎么做?

1 个答案:

答案 0 :(得分: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})"