32

こんにちは、より複雑なモデルを:sourceいつ使用するか、いつ使用するかを概念化するのに苦労しています。:class

ここに、友達がいるユーザーの例があります。

class User < ActiveRecord::Base
  ...
  has_many :friendships, :dependent => :destroy
  has_many :friends, :through => :friendships, :conditions => "status = 'accepted'"
  has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at
  has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at
end


class Friendship < ActiveRecord::Base
  attr_accessible :friend_id, :user_id, :status

  belongs_to :user
  belongs_to :friend, :class_name => "User", :foreign_key => 'friend_id'
end

:class_name誰かが友情の代わりになぜそれを説明できますか:source? これはペアリング (has_many + :source 、 belongs_to + :class_name) だけだからですか?

4

2 に答える 2

27

それらは概念的には同じですが、用途ごとに異なる必要があるだけです。

:sourceを使用しているときに、関連付けられたモデル名を定義するために (オプションで) 使用されますhas_many through:class_name単純なhas many関係で (オプションで) 使用されます。どちらも、Rails が独自にクラス名を判別できない場合にのみ必要です。API の has_manyのドキュメントは、こちら を参照してください。

于 2012-11-28T18:01:32.913 に答える
1

:source と :class_name の使用例を次に示します。

has_many :subscribers, through: :subscriptions, source: :user

has_many :people, class_name: "Person"

ご覧のとおり、スルー テーブルを使用すると、最終的にsourceelse you use を使用することになりますclass_name

このリンクのオプションの例を見てください: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

于 2016-10-10T03:54:52.670 に答える