user3097405
user3097405

Reputation: 823

How to create a record from the belongs_to association?

I have this association:

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

And I'm trying to understand the following behavior:

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">]>

Why #create_user adds user to todo_list (todo_list.user returns the user), but does not reflect the association when user.todo_lists is called?

EDITED:

Trying to create a record from the belongs_to side in a one-to-one relationship works when using #create_user!. It still does not hold true when creating a record from the belongs_to in a one-to-many relationship, even using #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 []>

Upvotes: 1

Views: 1971

Answers (1)

kunashir
kunashir

Reputation: 959

I think You have forgotten to save todo_list. Creating user don't save todo_list automaticlly and TodoList have foreign key not User (todo_list.user_id).

Upvotes: 1

Related Questions