Rails: :source => 之间的区别??和 :class_name =>??在模型中 [英] Rails: difference between :source => ?? and :class_name => ?? in models
问题描述
您好,对于更复杂的模型,我无法确定何时使用 :source
以及何时使用 :class
.
Hi I'm having trouble conceptualizing when to use :source
and when to use :class
for my more complex models.
这里我有一个用户和朋友的例子.
Here I have an example of users with friends.
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
有人能解释一下为什么 Friendship 是 :class_name
而不是 :source
吗?这是因为那只是配对(has_many + :source ,belongs_to + :class_name)?
Can someone explain why for Friendship it's :class_name
instead of :source
? Is this because that's just the pairing (has_many + :source , belongs_to + :class_name)?
推荐答案
它们在概念上是相同的,只是针对不同的用途而有所不同.
They are conceptually the same, just need to be different for different uses.
:source
用于(可选)在您使用 has_many through
时定义关联的模型名称;:class_name
用于(可选)在一个简单的 has many
关系中.仅当 Rails 无法自行找出类名时才需要两者.请参阅此处 API 中 has_many 的文档.
:source
is used (optionally) to define the associated model name when you're using has_many through
; :class_name
is used (optionally) in a simple has many
relationship. Both are needed only if Rails cannot figure out the class name on its own. See the documentation for has_many in the API here.
这篇关于Rails: :source => 之间的区别??和 :class_name =>??在模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!