Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 

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)?

like image 418
bigpotato Avatar asked Nov 28 '12 17:11

bigpotato


People also ask

What is source in Rails?

The source is used when you need Rails to know that you have creatively used has _many: through association. For example, a post can have many authors (but still one editor). We'll need to create a new table post_authorings.

What is polymorphic association in Rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.

What is association in Ruby on Rails?

Association in Rails defines the relationship between models. It is also the connection between two Active Record models. To figure out the relationship between models, we have to determine the types of relationship.


2 Answers

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.

like image 130
Tom Harrison Avatar answered Sep 24 '22 23:09

Tom Harrison


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

like image 43
Ravikanth Andhavarapu Avatar answered Sep 22 '22 23:09

Ravikanth Andhavarapu