0

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?

4

1 回答 1

1
u1.subscriptions << s1
[s1]

u1.subscriptions << s2
[s1,s2]

.. ..等等 向数组中添加元素,类似于 push 方法

s1.user = u1始终为用户对象赋值

s1.user = u2

它给了 u2

于 2013-01-24T09:28:31.053 回答