我正在尝试为我的数据库播种,但我遇到了这个错误,并且作为初学者不知道如何解决它。这是错误(rb.33指向bookmarks = Bookmarks.all):
vagrant@rails-dev-box:~/code/bookmarks$ rake db:seed
rake aborted!
NoMethodError: undefined method `all' for Bookmarks:Module
/home/vagrant/code/bookmarks/db/seeds.rb:33:in `<top (required)>'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.5/lib/active_support/dependencies.rb:223:in `load'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.5/lib/active_support/dependencies.rb:223:in `block in load'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.5/lib/active_support/dependencies.rb:214:in `load_dependency'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.5/lib/active_support/dependencies.rb:223:in `load'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.5/lib/rails/engine.rb:540:in `load_seed'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activerecord-4.0.5/lib/active_record/tasks/database_tasks.rb:154:in `load_seed'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activerecord-4.0.5/lib/active_record/railties/databases.rake:181:in `block (2 levels) in <top (required)>'
这是我的seeds.rb文件:
require 'faker'
# Create a User
user = User.new(
name: 'First Last',
email: 'firstlast@gmail.com',
password: 'password',
)
user.skip_confirmation!
user.save
#Create Bookmarks
10.times do
Bookmark.create!(
url: Faker::Internet.url
)
end
bookmarks = Bookmarks.all
#Create Topics
10.times do
Topic.create!(
name: Faker::Lorem.sentence
)
end
topics = Topic.all
users.each do |user|
3.times do
user.bookmarks << Bookmark.sample
end
end
topics.each do |topic|
3.times do
user.topics << Topic.sample
end
end
puts "Seed finished"
puts "#{User.count} users created"
puts "#{Bookmark.count} bookmarks created"
puts "#{Topic.count} topics created"
这是我的创建书签代码(我已经测试过并且有效):
def create
bookmark = Bookmark.where(url: params[:bookmark][:url]).first
@bookmark = bookmark.present? ? bookmark : Bookmark.new(bookmark_params)
if @bookmark.save
@bookmark.users << current_user
Rails.logger.info ">>>>>>>>>>>>> Bookmark: #{@bookmark.inspect}"
topic_names = params[:topic_names].split(' ')
topic_names.each do |topic_name|
name = topic_name.sub(/#/, '')
@bookmark.topics << Topic.find_or_create_by_name(name)
end
respond_to do |format|
format.html { redirect_to @bookmark, notice: 'Bookmark was successfully created.' }
format.json { render action: 'show', status: :created, location: @bookmark }
end
else
respond_to do |format|
format.html { render action: 'new' }
format.json { render json: @bookmark.errors, status: :unprocessable_entity }
end
end
end
非常感谢任何帮助!
答案 0 :(得分:2)
NoMethodError:未定义的方法`all&#39;对于书签:模块
rails中的模型名称通常是单数和,因为你的种子中已经有Bookmark.create
所以我猜你有一个错字。它应该是Bookmark.all not Bookmarks.all
bookmarks = Bookmark.all