Rails: difference between :source => ?? and :class_name => ?? in models

前端 未结 2 1517
傲寒
傲寒 2020-12-08 19:43

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 use

相关标签:
2条回答
  • 2020-12-08 20:19

    They are conceptually the same, just need to be different for different uses.

    :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.

    0 讨论(0)
  • 2020-12-08 20:36

    Here are examples of usage of :source and :class_name.

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

    has_many :people, class_name: "Person"

    As you can see when you use a through table you end up using source else you use class_name.

    Look at the option examples in this link: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

    0 讨论(0)
提交回复
热议问题