OSDN Git Service

5bc9a813f55a1be806c0d7c5fda0f12b518173c4
[elecoma/elecoma.git] / app / models / supplier.rb
1 class Supplier < ActiveRecord::Base
2   acts_as_paranoid
3   belongs_to :prefecture
4   has_many :products
5   #DEFAULT_IDは仕入先不使用時のIDとして定義
6   #id=1のデータは編集不可、削除不可
7   DEFAULT_SUPPLIER_ID = 1
8   SHISYAGONYU, KIRISUTE, KIRIAGE = 0, 1, 2
9   TAX_RULE_NAMES = { SHISYAGONYU => "四捨五入", KIRISUTE => "切り捨て", KIRIAGE => "切り上げ"}  
10   
11   validates_presence_of :name
12   validates_uniqueness_of :name
13   validates_length_of :name, :maximum => 50
14
15   validates_presence_of :zipcode01, :zipcode02
16   validates_numericality_of :zipcode01, :zipcode02, :allow_blank=>true
17   validates_length_of :zipcode01, :is => 3, :allow_blank=>true
18   validates_length_of :zipcode02, :is => 4, :allow_blank=>true
19   validates_associated :prefecture
20   validates_presence_of :prefecture_id,:address_city, :address_detail
21   validates_length_of :address_city, :address_detail, :maximum => 100
22   
23   validates_presence_of :contact_name
24   validates_length_of :contact_name, :maximum => 50
25   
26   validates_presence_of :tel01, :tel02, :tel03
27   validates_numericality_of :tel01, :tel02, :tel03, :allow_blank => true
28   validates_length_of :tel01, :tel02, :tel03, :maximum => 6, :allow_blank => true
29   
30   validates_numericality_of :fax01, :fax02, :fax03, :allow_blank => true
31   validates_length_of :fax01, :fax02, :fax03, :maximum => 6, :allow_blank => true
32   
33   validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :allow_blank => true
34   
35   validates_inclusion_of :percentage, :in => (0..100), :allow_blank => true
36   
37   validates_length_of :free_comment, :maximum => 10000 , :allow_blank => true
38   validates_inclusion_of :tax_rule, :in => [SHISYAGONYU, KIRISUTE, KIRIAGE] , :allow_blank => true
39
40   before_update :check_default
41   before_destroy :check_default_and_products
42   
43   def validate
44     super
45     # FAX どれかが入力されている時だけ検証
46     if not [fax01, fax02, fax03].all?(&:blank?)
47       fax_items = %w(fax01 fax02 fax03)
48       errors.add_on_blank fax_items, "が入力されていません"
49     end
50   end
51   
52   def tel
53     "#{tel01}-#{tel02}-#{tel03}" unless tel01.blank? or tel02.blank? or tel03.blank? 
54   end
55   
56   def fax
57     "#{fax01}-#{fax02}-#{fax03}" unless fax01.blank? or fax02.blank? or fax03.blank? 
58   end
59   
60   def prefecture_name
61     prefecture && prefecture.name
62   end
63   
64   def tax_rule_label
65     TAX_RULE_NAMES[tax_rule] unless tax_rule.blank?
66   end
67   def check_default_and_products
68     check_default
69     #直接URL入力で商品を持っている仕入先を削除防止するため
70     unless self.products.blank?
71       raise ActiveRecord::ReadOnlyRecord
72     end
73   end
74   def check_default
75     #id=1のデータはデフォルトの状態のみで、編集不可、削除不可
76     if self.id == DEFAULT_SUPPLIER_ID
77       raise ActiveRecord::ReadOnlyRecord
78     end
79   end
80 end