2016-05-01 112 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

相關問題