Reputation: 1279
In my seeds file I have a bunch of objects which belong_to and object which belongs_to a user.
So I have User which has a Library which has_many books
In my seeds file I set up some books like:
book = Book.new
book.attribute = "attribute"
book.save
library = Library.new
library.books << book
library.save
user = User.new
user.library = library
user.save
What happens is that a User is created which has the Library as expected, yet no books are created.
When I run rails c and do
Book.all
I see that there are 0 books.
Why is this happening?
Additionally, I create a pool of books and 5 users, and for each user I assign some of the same books created above to that users library.
However, neither
User.find(1).library.books
return anything or
Book.all
return anything.
User:
class User < ActiveRecord::Base
before_create :create_library, only: [:new, :create]
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
after_create :send_welcome_email
has_one :library, dependent: :destroy
end
Library:
class Library < ActiveRecord::Base
belongs_to :user
has_many :books, dependent: :destroy
end
Book:
class Book < ActiveRecord::Base
validates :title, :author, presence: true
belongs_to :library
has_many :sources
has_one :cover, class_name: 'BookCover', dependent: :destroy
mount_uploader :cover, BookCoverUploader
accepts_nested_attributes_for :sources, allow_destroy: true
accepts_nested_attributes_for :cover, allow_destroy: true
end
Upvotes: 1
Views: 1685
Reputation: 625
As @newmediafreak mentioned, you may have validations on the Book class that prevent it from being saved.
I recommend creating your has_many
and has_one
instances through the associations:
user = User.create!
library = user.library.create!
book = user.books.create!(attribute: 'my attribute')
Using the Object.create!
syntax will cause errors if there are any problems saving. Object.save
fails silently.
You have a typo/error: user.library = Library
should be user.library = library
, but I still recommend creating library and the books through the association.
Upvotes: 1