Ruby on rails 为不由模型表示的表生成种子
如果在rails应用程序中,我有一个表示两个对象之间关联的中间表(例如,books and authors:一本书有许多作者,而一位作者有许多书),我如何用Ruby on rails 为不由模型表示的表生成种子,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 3.2,如果在rails应用程序中,我有一个表示两个对象之间关联的中间表(例如,books and authors:一本书有许多作者,而一位作者有许多书),我如何用seeds.rb文件填充该表 更新 class Author < ActiveRecord::Base has_and_belongs_to_many :books # ... end class Book < ActiveRecord::Base has_and_belongs_to_many :a
seeds.rb
文件填充该表
更新
class Author < ActiveRecord::Base
has_and_belongs_to_many :books
# ...
end
class Book < ActiveRecord::Base
has_and_belongs_to_many :authors
# ...
end
类作者
我假设你有一个has\u和\u属于\u两者之间的许多关联。如果是这种情况,那么您可以执行以下操作:
# seeds.rb
author = Author.create(name: 'Mark Twain')
author.books << Book.new(title: 'The Adventures of Tom Sawyer')
为什么没有一个模型来表示这些数据?在大多数情况下,您需要一个模型来表示存储在数据库中的任何信息
一旦你有了模型,你应该能够通过做一些简单的事情来轻松地创建你的种子
BookAuthors.create([
{book_id: 1, author_id: 2}
])
在你的seeds.rb文件中。我得到了NoMethodError:undefined method
发布你的app/models/book.rb
和app/models/author.rb
文件,我来看看
BookAuthors.create([
{book_id: 1, author_id: 2}
])