【问题标题】:Rails: difference between :source => ?? and :class_name => ?? in modelsRails::source => ?? 之间的区别和 :class_name => ??在模型中
【发布时间】:2012-11-28 17:46:20
【问题描述】:

您好,对于更复杂的模型,何时使用 :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)吗?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    它们在概念上是相同的,只是不同用途需要不同。

    :source 用于(可选)在您使用has_many through 时定义关联的模型名称; :class_name 用于(可选)简单的has many 关系。仅当 Rails 无法自行确定类名时才需要两者。请参阅documentation for has_many in the API here

    【讨论】:

    • 我还是有点困惑。我在我的大部分has_many :through 关联中使用:class_name,它工作正常。一个只是另一个的别名吗?当您说“只有在 Rails 无法弄清楚时才需要两者……”时,您的意思是应该同时提供 :class_name:source 吗?那有必要吗? (我问的原因是因为我刚刚在我的代码中找到了一个兼具两者的关联,这让我用谷歌搜索一劳永逸地发现了区别)。到目前为止,感谢您的回答,我想我非常接近了解其中的区别! (如果有的话……)
    • 唯一一次我认为你需要做源代码和类名是如果你正在做一个不同的有很多直通名称并且有一个子类模型。例如想象梦幻足球。您有一个通过 user_leagues 属于联赛的 User、User::Player 和 User::Commissioner。如果您通过球员联赛编写了许多球员并想引用 User::Player,那么您将需要 class_name 和 source。至少我是这么认为的;)。
    【解决方案2】:

    以下是 :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

    【讨论】:

      猜你喜欢
      • 2017-04-29
      • 2014-03-21
      • 2011-07-13
      • 2013-04-18
      • 2015-10-01
      • 2012-06-28
      • 2015-03-26
      相关资源
      最近更新 更多