Rails:区别:source => ?? 和:class_name => ?? 在模型中

big*_*ato 29 ruby-on-rails

嗨,我无法概念化何时使用: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
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么友谊:class_name而不是:source?这是因为那只是配对(has_many +:source,belongs_to +:class_name)?

Tom*_*son 25

它们在概念上是相同的,只是需要针对不同的用途而有所不同.

:source用于(可选)在您使用时定义关联的模型名称has_many through; :class_name(可选地)以简单的has many关系使用.只有当Rails无法自己找出类名时才需要这两者.请在此处查看API中has_many文档.