AWDwR "Chapter15 More Active Record"
ãã£ã¨Active Recordï¼ ãã£ã¨ã¢ããã«ã®iMac G5欲ããï¼
Act as
DBã®ãã¼ã¿ããªã¹ãæ§é ãããªã¼æ§é ã®ããã«æ±ããã¨ãã§ããããã¹ãããããªã¼ã!
ã¾ããªã¹ãæ§é ã®å ´åã¯ãã¼ãã«ã«positionã¨ããã«ã©ã ãå®ç¾©ãã¦ã¢ãã«ã以ä¸ã®ããã«å®ç¾©ã
class Parent < ActiveRecord::Base has_many :children, :order => position end class Child < ActiveRecord::Base belongs_to :parent acts_as_list :scope => :parent_id end
ããããã¨childrenã¯ä»¥ä¸ã®ããã«ãã¦æ±ããã
parent.children[0].name parent.children[0].first? # å é ? parent.children[2].last? # æå¾? parent.children[1].lower_item # ä¸ã¤å¾ parent.children[1].higher_item # ä¸ã¤å parent.children[0].move_lower # ä¸ã¤åã«ç§»åããã parent.children[2].move_higher # ä¸ã¤å¾ã«ç§»åããã parent.children[0].move_to_bottom # æå¾ã«ç§»åããã parent.children[2].move_to_top # å é ã«ç§»åããã
ãã ãæä½ããå¾ã¯reloadãã¨ããªãã¨parentã¯ããã£ã¦ãããªããã注æã
次ã¯ããªã¼æ§é ããã®å ´åã¯ãã¼ãã«ã«parent_idã¨ããã«ã©ã ãå®ç¾©ãã¦ã¢ãã«ã以ä¸ã®ããã«å®ç¾©ã
class Category < ActiveRecord::Base acts_as_tree end
ããããã¨ä»¥ä¸ã®ããã«ãã¦æ±ããã
sub = root.children.create sub_sub = sub.children.create sub_sub_sub = sub_sub.children.create root.children.first.name root.children.size root.children.find(:all, ;conditions => "name='Book'") sub.parent.name
Aggregation
è¤æ°ã®ã¯ã©ã¹ãããªãã¢ãã«ã®ãã¼ã¿ãä¸ã¤ã®ãã¼ãã«ã«æ ¼ç´ããã®ãã¢ã°ãªã²ã¼ã·ã§ã³ãCustomerã¯ã©ã¹ã®nameå±æ§ã«Nameã¯ã©ã¹ããããã³ã°ãã¦ããå ´åã¯
class Customer < ActiveRecord::Base composed_of :name, :class_name => Name, :mapping => [[:first_name, :first], [:last_name, :last]] end
ã¨å®ç¾©ãNameã¯ã©ã¹ã®å±æ§ã«ã¢ã¯ã»ã¹ããã«ã¯
customer.name.first customer.name.last
ã¨ãããNameã¯ã©ã¹ã®å±æ§ãå¤æ´ããã«ã¯æ°ããã¤ã³ã¹ã¿ã³ã¹ãä½ã£ã¦å±æ§ã«ã»ãããããã¨ã
customer.name = Name.new(firstname, lastname) customer.save
Single Table Inheritance
ç¶æ¿é¢ä¿ã®ã¯ã©ã¹ã®ãªãã¸ã§ã¯ããä¸ã¤ã®ãã¼ãã«ã«æ ¼ç´ããåä¸ãã¼ãã«ç¶æ¿ã£ã¦ãã¤ãããã®å ´åã¯ãã¼ãã«ã«typeã¨ããã«ã©ã ãå®ç¾©ãã¦ä»¥ä¸ã®ããã«ã¢ãã«ãå®ç¾©ããã
class Person < ActiveRecord::Base end class Customer < Person end class Employee < Person end class Manager < Employee end
ã¯ã©ã¹åã¯person.classã§åå¾å¯è½ã
Validation
ããªãã¼ã·ã§ã³ã¯ãããããããã
validate # ä¿åæã«ç¢ºèª validate_on_create # æ°è¦ä¿åæã®ã¿ç¢ºèª validate_on_update # æ´æ°æã®ã¿ç¢ºèª validates_acceptance_of # ãã§ãã¯ããã¯ã¹ããã§ãã¯ããã¦ãããã¨ã確èªï¼è¦ç´ã®æ¿èªãªã©ã«ä½¿ããããªï¼ validates_associated # é¢é£ä»ãããããªãã¸ã§ã¯ããç¢ºèª validates_confirmation_of # 確èªç¨ã®å±æ§ã¨ä¸è´ãã¦ãããã©ããã確èªï¼ç¢ºèªç¨ã®å±æ§åã¯_confirmationãä»ããããã¹ã¯ã¼ãã®ç»é²ã®ç¢ºèªã«ãã使ããããï¼ validates_each # è¤æ°ã®å±æ§ããããã¯ã使ã£ã¦ç¢ºèª validates_exclusion_of # æå®ããå¤ã®ã»ããã«å«ã¾ãã¦ããªããã¨ãç¢ºèª validates_format_of # æå®ããæ£è¦è¡¨ç¾ã«ããããããã¨ãç¢ºèª validates_inclusion_of # æå®ããå¤ã®ã»ããã«å«ã¾ãã¦ãããã¨ãç¢ºèª validates_length_of # æååã®é·ããæå®ãããé·ãã§ãããã¨ã確èªï¼æ大å¤ãæå°å¤ãè¨å®å¯è½ï¼ validates_numericality_of # æ°å¤ã§ãããã¨ã確èªï¼only_integer => trueã¨ããã¨æ´æ°ã§ãããã¨ã確èªï¼ validates_presence_of # 空ã§ãªããã¨ãç¢ºèª validates_uniqueness_of # ã¦ãã¼ã¯ã§ãããã¨ã確èª
ç¶ãã¯ã¾ãã