Amit
Amit

Reputation: 539

ActiveRecord: difference between collection << object and association = (associate)

Let us take an example:

class Subscription < ActiveRecord::Base
 belongs_to :user
end

class User < ActiveRecord::Base
 has_many :subscriptions
end

u1 =User.new
s1 = Subscription.new

According to me, the following two lines should be equivalent:

u1.subscriptions << s1, and 
s1.user = u1

However, it seems that it is not the case. After executing the first line, u1.subscriptions_ids returns [1] but after executing the second line, u1.subscriptions_ids returns [].

What could be the reason for this?

Upvotes: 0

Views: 490

Answers (1)

Sachin R
Sachin R

Reputation: 11876

u1.subscriptions << s1
[s1]

u1.subscriptions << s2
[s1,s2]

.. ..and so on adds element to array similar to push method

whereas s1.user = u1 always assign value to user object

s1.user = u2

it gives u2

Upvotes: 1

Related Questions