Rails rake db:seed没有创建属于另一个对象的对象?

时间:2015-05-20 04:21:39

标签: ruby-on-rails database activerecord rake seeding

在我的种子文件中,我有一堆属于属性的对象和属于用户的对象。

所以我的用户有一个有很多书的图书馆

在我的种子文件中,我设置了一些书籍:

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

请注意,为了补充为图书模型创建相应的书籍,我只需传递&#34; remote_cover_url&#34;在book模型上,载波用于在书上创建BookCover。

1 个答案:

答案 0 :(得分:1)

正如@newmediafreak所提到的,您可能会在Book类上进行验证,以防止它被保存。

我建议您通过创建has_manyhas_one个实例

user = User.create! library = user.library.create! book = user.books.create!(attribute: 'my attribute')

如果存在任何问题,使用Object.create!语法将导致错误。 Object.save无声地失败。

编辑10:48 PDT

您有错误/错误:user.library = Library应为user.library = library,但我仍建议您通过关联创建图书馆和图书。