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

嗨,我无法概念化何时使用:source和何时使用:class for my more complex model。

这里我有一个用户和朋友的例子。

 class User  :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  "User", :foreign_key => 'friend_id' end 

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

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

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

以下是使用的示例:source和:class_name。

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

has_many :people, class_name: "Person"

正如您在使用直通表时所看到的那样,您最终使用的是source而您使用的是class_name

请查看此链接中的选项示例: http : //api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many