顯示具有 has_one 標籤的文章。 顯示所有文章
顯示具有 has_one 標籤的文章。 顯示所有文章

2008年10月27日 星期一

Has_one with :source_type

http://www.javaeye.com/topic/129195


class Client < ActiveRecord::Base
has_many :contact_cards
has_many :business_contacts,
:through => :contact_cards,
:source => :contact, <= 跟 as => :this_item 的this_item 一樣
:source_type => 'Business'
end

class Business < ActiveRecord::Base
has_many :contact_cards, :as => :contact
end

class ContactCard < ActiveRecord::Base
belongs_to :client
belongs_to :contact, :polymorphic => true
end

User.first.business_cards <= 第一個user的contact card of bussiness category

2008年8月21日 星期四

has_one, has_many ,through

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M000979


has_one
  • Account#build_beneficiary (similar to Beneficiary.new("account_id" => id))
  • Account#create_beneficiary (similar to b = Beneficiary.new("account_id" => id); b.save; b)
has_many
  • Firm#clients.build (similar to Client.new("firm_id" => id))
  • Firm#clients.create (similar to c = Client.new("firm_id" => id); c.save; c)


Some examples:

[user model]
has_many :record_comments, :through => :records, :source => :comments, :order => "created_at DESC", :limit => 6

has_many :demands, :foreign_key => 'demander_id', :class_name => 'Call'
has_many :accepts, :foreign_key => 'accepter_id', :class_name => 'Call'

[call model]
belongs_to :demander, :foreign_key => 'demander_id', :class_name => 'User'
belongs_to :accepter, :foreign_key => 'accepter_id', :class_name => 'User'