未定义的局部变量/方法用户

时间:2015-11-10 00:11:52

标签: ruby-on-rails

我正在学习如何使用faker gem将数据植入我的项目中。我的项目是一个todo列表,允许用户检查和添加项目。我学会了如何创建自己的RandomData,但是我在修改教程时遇到了麻烦。我也不确定我是否适应'这对教程是正确的,所以我希望我提供足够的信息。

运行rake db:reset错误时如下:

NameError: undefined local variable or method `user' for main:Object
itoff/db/seeds.rb:13:in `block in <top (required)>'
itoff/db/seeds.rb:11:in `times'
itoff/db/seeds.rb:11:in `<top (required)>'

我发现它在我的假物品循环中,但我不确定我做错了什么。请记住,我是Ruby on Rails的新手,所以如果我错过了一些明显的东西,我很抱歉。

使用装饰和faker宝石。

(最后的问题:我能做得更好吗?我还应该做些什么/专注于在轨道上的红宝石上做得更好?)

seeds.rb

#Create fake user
5.times do
  user = User.new(
    email: Faker::Internet.email,
    password: Faker::Lorem.characters(10)
  )
  user.skip_confirmation!
  user.save!
end

#Create fake items
10.times do
  item = Item.create!(
    user: user.sample,
    name: Faker::Lorem.sentence
  )
end

puts "Seed finished"
puts "#{User.count} users created"
puts "#{Item.count} items created"

我的 items_controller.rb

class ItemsController < ApplicationController

  def create
    @item = current_user.items.new(item_params)

    if @item.save
      redirect_to current_user, notice: "Item was saved successfully."
    else
      flash[:error] = "Error creating item. Please try again."
      render :new
    end
  end


  def destroy
     @item = Item.find(params[:id])

     if @item.destroy
       flash[:notice] = "\"#{@item.name}\" was deleted successfully."
       redirect_to action: :index
     else
       flash[:error] = "There was an error deleting the item."
       render :show
     end
   end

  private
  def item_params
    params.require(:item).permit(:name)
  end
end

item.rb的

class Item < ActiveRecord::Base
  belongs_to :user
  validates :description, presence: true
end

user.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

         has_many :items
end

1 个答案:

答案 0 :(得分:1)

有两个问题。出现错误是因为user文件中的seeds.rb变量超出了范围。它位于do块内。此外,您应该使用User类,而不是实例:

5.times do
  user = User.new( # This is inside of a do block
    email: Faker::Internet.email,
    password: Faker::Lorem.characters(10)
  )
  user.skip_confirmation!
  user.save!
end

#Create fake items
10.times do
  item = Item.create!(
    user: user.sample, # Which user? There is no user in this scope
    name: Faker::Lorem.sentence
  )
end

您需要做的是在.sample课程上致电User;但是,你不能用这种方式来吸引用户。您需要随机抓取id

#Create fake items
user_ids = User.ids # See the capitalization of User
10.times do
  item = Item.create!(
    user_id: user_ids.sample,
    name: Faker::Lorem.sentence
  )
end

或者从所有id中抓取id。您可以执行此操作:User.order("RANDOM()").first,这将获取随机User模型。这将是:

#Create fake items
10.times do
  item = Item.create!(
    user: User.order("RANDOM()").first
    name: Faker::Lorem.sentence
  )
end