mailr/app/models/contact.rb

46 lines
1.4 KiB
Ruby
Raw Normal View History

2012-03-10 18:08:39 +01:00
class Contact < ActiveRecord::Base
2012-03-30 19:31:23 +02:00
validates_length_of :name, :within => 3..20
2012-03-10 18:08:39 +01:00
validates_length_of :email, :within => 5..50
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
validates_length_of :info, :maximum => 100
2012-03-30 19:31:23 +02:00
validate :check_unique_name, :on => :create
default_scope :order => 'name ASC'
2012-03-10 18:08:39 +01:00
belongs_to :user
def self.getPageForUser(user,page,sort_field,sort_dir)
if sort_field
if Contact.attribute_method?(sort_field) == true
order = sort_field
sort_dir == 'desc' ? order += ' desc' : sort_dir
end
end
Contact.paginate :page => page , :per_page => $defaults["contacts_per_page"], :conditions=> ['user_id = ?', user.id],:order => order
end
2012-03-30 19:31:23 +02:00
def check_unique_name
if !Contact.where('upper(name) = ? and user_id = ?',name.upcase,user_id).size.zero?
errors.add(:name, :not_unique)
2012-03-10 18:08:39 +01:00
end
end
def export
fields = []
2012-03-30 19:31:23 +02:00
fields << name || ""
2012-03-10 18:08:39 +01:00
fields << email || ""
fields << info || ""
fields.join(';')
end
def self.import(user,line)
fields = line.split(/;/)
2012-03-30 19:31:23 +02:00
contact = user.contacts.build( :name => fields[0].strip,
:email => fields[1].strip,
:info => fields[2].strip)
2012-03-10 18:08:39 +01:00
contact.save!
end
end