Ruby on Rails Self-referential has_many :through associations
第äºåå å
ã¨ããããã§ï¼Railsã§èªå·±åç
§å¤å¯¾å¤ã¢ã½ã·ã¨ã¼ã·ã§ã³ãhas_many :throughãå©ç¨ãã¦å®è£
ãã¦ã¿ãã¡ã¢ï¼
ä»åç¨æãããµã³ãã«ã¯Webãã¼ã¸ããªã³ã¯ã§ç¹ãã£ã¦ãã¤ã¡ã¼ã¸ï¼ERDã¯ä»¥ä¸ã®ç»åã¿ãããªæãï¼
ããããã®modelã¯ãããªæãï¼
class Page < ActiveRecord::Base # Associations has_many :links_sent, :foreign_key => 'from_page_id', :class_name => 'Link', :dependent => :destroy has_many :links_received, :foreign_key => 'to_page_id', :class_name => 'Link', :dependent => :destroy has_many :links_sent_pages, :through => :links_sent, :source => :link_to_page has_many :links_received_pages, :through => :links_received, :source => :link_from_page # validates validates_uniqueness_of :url end
class Link < ActiveRecord::Base # Associations belongs_to :link_from_page, :foreign_key => 'from_page_id', :class_name => 'Page' belongs_to :link_to_page, :foreign_key => 'to_page_id', :class_name => 'Page' end
script/consoleã§ç¢ºèªãã¦ã¿ãï¼
Link主ä½ã§ä½æããå ´å
ruby script/console >> Page.count => 0 >> from_page = Page.new(:url => "http://example.com/page/from") >> to_page = Page.new(:url => "http://example.com/page/to") >> to_page.links_received_pages => [] >> Link.create(:link_from_page => from_page, :link_to_page => to_page) >> to_page.links_received_pages => [#<Page:0xb7ae42ac @attributes={"body"=>nil, "url"=>"http://example.com/page/from", "id"=>"1"}>] >> Page.count => 2 >> Link.count => 1
Page主ä½ã§ä½æããå ´å
ruby script/console >> Page.count => 0 >> from_page = Page.create(:url => "http://example.com/page/from") >> from_page.links_sent_pages => [] >> from_page.links_sent.create(:link_to_page => Page.new(:url => "http://example.com/page/to")) >> from_page.links_sent_pages => [#<Page:0xb7ca56c0 @attributes={"body"=>nil, "url"=>"http://example.com/page/to", "id"=>"2"}>] >> Page.count => 2 >> Link.count => 1
åé¤ãã¦ã¿ãï¼ï¼ä¸ã®ç¶ãï¼
ruby script/console >> Page.count => 2 >> Link.count => 1 >> from_page.destroy >> Page.count => 1 >> Link.count => 0
ãã®åç´ãªã¢ãã«ãªãhabtm使ãã°ãããã ãã©ï¼ããããã¯has_many :throughãæµè¡ãããã®ã§ï¼
ä»åã®ãµã³ãã«ã§ã¯è¼ãã¦ãªããã©ï¼å®éã«ä½ãéã«ã¯Linkãä»ã®ã¢ãã«ã¨é¢é£ãã¦ããã§ãã£ã¡ã§ãã£ã¦ã¿ãï¼
ã³ãã¯ï¼has_manyã®ç¬¬1å¼æ°ã«ä¸ããååãåããããããããã¨ï¼ï¼çµ¶å¯¾ã«ã©ã£ã¡ããªã³ã¯å ï¼ãªã³ã¯å ï¼ã£ã¦æ··ä¹±ããããï¼çµé¨è èªãï¼
ããã¾ã