ekrako
ekrako

Reputation: 179

Using Model limitation in a view

I trying to follow one of rails basic rules DRY (don't repeat yourself) I have the following model

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

and in the form I'm limiting the textarea with Java script

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

I want to use the maximum value from the validation in java script function.

How do i do it?

Upvotes: 1

Views: 63

Answers (1)

KL-7
KL-7

Reputation: 47608

The easiest solution would be to extract magic number 140 into a constant and then use it both in validation:

class Micropost < ActiveRecord::Base

  MAX_CONTENT_LENGTH = 140

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

end

and inside the view:

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

Upvotes: 2

Related Questions