在我的种子文件中,我有一堆属于属性的对象和属于用户的对象。
所以我的用户有一个有很多书的图书馆
在我的种子文件中,我设置了一些书籍:
book = Book.new
book.attribute = "attribute"
book.save
library = Library.new
library.books << book
library.save
user = User.new
user.library = library
user.save
创建的用户是按预期创建了库,但没有创建书籍。
当我运行rails c并执行
时Book.all
我看到有0本书。
为什么会这样?
此外,我创建了一个书库和5个用户,并为每个用户将上面创建的一些相同书籍分配给该用户库。
但是,
User.find(1).library.books
返回任何内容或
Book.all
返回任何内容。
用户:
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
库:
class Library < ActiveRecord::Base
belongs_to :user
has_many :books, dependent: :destroy
end
图书:
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
答案 0 :(得分:1)
正如@newmediafreak所提到的,您可能会在Book类上进行验证,以防止它被保存。
我建议您通过创建has_many
和has_one
个实例:
user = User.create!
library = user.library.create!
book = user.books.create!(attribute: 'my attribute')
如果存在任何问题,使用Object.create!
语法将导致错误。 Object.save
无声地失败。
您有错误/错误:user.library = Library
应为user.library = library
,但我仍建议您通过关联创建图书馆和图书。