【发布时间】:2014-03-24 19:12:52
【问题描述】:
我编写了自己的代码,应该在数据库中创建一个新的性能(模型)条目。我对这应该如何工作缺乏基本的了解,但我也不知道要搜索什么。
我将此文件放在我的项目根目录中。 当我从命令行运行文件时,出现以下错误:
C:/rubyProjects/dads/fileParser.rb:17:in `<main>': uninitialized constant Performance (NameError)
这是我的代码:
require 'date'
#require 'Performance'
#require 'performer'
file_name = File.basename("app\assets\documents\Location-2003.11.11-ArtistsName-ArtistName2.txt", ".txt")
performance_array = file_name.split("-")
location = performance_array[0]
date = performance_array[1]
begin
date = Date.parse(date)
rescue ArgumentError
date = Date.parse("31-02-2010")
end
#Need to access Performance here but it fails
performance = Performance.create(file_name: file_name,
date: date,
location: location)
performance_array.drop(2).each do |performer_name|
puts artist_name
#save performer in db if doesnt exist
performer = Performer.find_by_name(performer_name)
if performer == nil
performer = Performer.create(name: performer_name)
end
#create performer to performance relationship
performance.performers << performer
end
这是我的模型文件\app\models\performance.rb:
class Performance < ActiveRecord::Base
validates :file_name, presence: true, length: { maximum: 50 }, uniqueness: { case_sensitive: false }
validates :date, length: { maximum: 30 }
validates :location, length: { maximum: 50 }
has_many :performer_performances, dependent: :destroy
has_many :performers, through: :performer_performances
def has_performer?(performer)
performer_performances.find_by(performer_id: performer.id)
end
def include! (performer)
performer_performances.create!(performer_id: performer.id)
end
end
【问题讨论】:
-
app/models目录中是否有名为Performance的模型?你能分享一下模型的详细信息吗? -
您没有使用模块或类?这段代码在顶层结束。
-
@KirtiThorat 我将其包含在问题中。我用 rspec 测试我的模型并且它可以工作(我使用来自 ruby.railstutorial.org 的基本测试)
-
run the file from the cmd是什么意思?您是否像ruby fileParser.rb那样执行它,那么在这种情况下,Rails 环境未加载。所以你必须require特定的类。
标签: ruby ruby-on-rails-4