2016-05-01 117 views
1

我有这样的联想:如何从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增加usertodo_listtodo_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 []> 

回答

1

我想你忘了保存todo_list。 创建用户不会自动保存todo_list,并且TodoList的外键不是用户(todo_list.user_id)。

+0

使用'todo_list.save'确实有效。但为什么在关联的另一端('user.todo_lists.create'),'user.save'没有必要? – user3097405

+0

这是没有必要的另一方面,因为,我认为,'todo_list'创建像这样的参数:'todo_list.create(user:user),我不确定细节,但在这个意思。 – kunashir

+0

谢谢@kunashir,但它仍然没有意义。我编辑了我的问题,将行为与'一对一'关系进行比较。 – user3097405

相关问题