Ich habe diesen Verein:Wie erstelle ich einen Datensatz aus der assignes_to-Assoziation?
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
Und ich versuche folgendes zu verstehen Verhalten:
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">]>
Warum #create_user
fügt user
-todo_list
(todo_list.user
kehrt die user
), aber spiegelt nicht die Assoziation, wenn user.todo_lists
genannt wird?
EDITED:
einen Datensatz aus der belongs_to
Seite in einer one-to-one
Beziehung zu erstellen Versuch funktioniert, wenn #create_user!
verwenden. Es gilt immer noch nicht beim Erstellen eines Datensatzes aus der belongs_to
in einer one-to-many
Beziehung, auch unter Verwendung #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 []>
Die Verwendung von 'todo_list.save' funktioniert. Aber warum auf der anderen Seite der Assoziation ('user.todo_lists.create') ist die' user.save' nicht notwendig? – user3097405
Es ist nicht notwendig auf der anderen Seite, weil, denke ich, 'todo_list' mit Params erstellen wie:' todo_list.create (user: user), bin ich nicht sicher in Details, aber die Bedeutung in diesem. – kunashir
Danke @kunashir, aber es macht immer noch keinen Sinn. Ich habe meine Frage bearbeitet, um das Verhalten mit der Eins-zu-eins-Beziehung zu vergleichen. – user3097405