我有这个协会:
user.rb
class User < ActiveRecord::Base
has_many :todo_lists
has_one :profile
end
todo_list.rb
class TodoList < ActiveRecord::Base
belongs_to :user
end
profile.rb
class Profile < ActiveRecord::Base
belongs_to :user
end
我试图理解以下行为:
todo_list = TodoList.create(name: "list 1")
todo_list.create_user(username: "foo")
todo_list.user
#<User id: 1, username: "foo", created_at: "2016-05-01 07:09:05", updated_at: "2016-05-01 07:09:05">
test_user = todo_list.user
test_user.todo_lists # returns an empty list
=> #<ActiveRecord::Associations::CollectionProxy []>
test_user.todo_lists.create(name: "list 2")
test_user.todo_lists
=> #<ActiveRecord::Associations::CollectionProxy [#<TodoList id: 2, name: "list 2", user_id: 1, created_at: "2016-05-01 07:15:13", updated_at: "2016-05-01 07:15:13">]>
为什么#create_user
将user
添加到todo_list
(todo_list.user
会返回user
),但在user.todo_lists
被调用时不反映关联?
已编辑:
使用belongs_to
时,尝试在one-to-one
关系中从#create_user!
侧创建记录。在belongs_to
关系中one-to-many
创建记录时,即使使用#create_user!
,它仍然不成立。
profile = Profile.create(first_name: "user_one")
profile.create_user!(username: "user_one username")
profile.user
=> #<User id: 6, username: "user_one username", created_at: "2016-05-01 18:22:31", updated_at: "2016-05-01 18:22:31">
user_one = profile.user
=> #<User id: 6, username: "user_one username", created_at: "2016-05-01 18:22:31", updated_at: "2016-05-01 18:22:31">
user_one.profile # the relationship was created
=> #<Profile id: 2, first_name: "user_one", user_id: 6, created_at: "2016-05-01 18:22:09", updated_at: "2016-05-01 18:22:31">
todo_list = TodoList.create(name: "a new list")
todo_list.create_user!(username: "user of a new list")
todo_list.user
=> #<User id: 7, username: "user of a new list", created_at: "2016-05-01 18:26:27", updated_at: "2016-05-01 18:26:27">
user_of_new_list = todo_list.user
=> #<User id: 7, username: "user of a new list", created_at: "2016-05-01 18:26:27", updated_at: "2016-05-01 18:26:27">
user_of_new_list.todo_lists #still does not create user from todo_list
=> #<ActiveRecord::Associations::CollectionProxy []>
答案 0 :(得分:1)
我想你忘了保存todo_list
。
创建用户不会自动保存todo_list,TodoList的外键不是User(todo_list.user_id)。