如何从belongs_to关联创建记录?
问题描述:
我有这样的联想:如何从belongs_to关联创建记录?
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
被称为没有体现出联想?
编辑:
试图在一个one-to-one
关系创建从belongs_to
侧的记录使用#create_user!
时的作品。即使使用#create_user!
,在belongs_to
关联中创建记录时,它仍然不成立。
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 []>
答
我想你忘了保存todo_list
。 创建用户不会自动保存todo_list,并且TodoList的外键不是用户(todo_list.user_id)。
使用'todo_list.save'确实有效。但为什么在关联的另一端('user.todo_lists.create'),'user.save'没有必要? – user3097405
这是没有必要的另一方面,因为,我认为,'todo_list'创建像这样的参数:'todo_list.create(user:user),我不确定细节,但在这个意思。 – kunashir
谢谢@kunashir,但它仍然没有意义。我编辑了我的问题,将行为与'一对一'关系进行比较。 – user3097405