我编写了自己的代码,该代码应该在数据库中创建一个新的Performance(模型)条目。我对这应该如何工作缺乏基本的了解,但我不知道要搜索什么。
我将此文件放在我的项目根目录中。 当我从命令行运行该文件时,我收到以下错误:
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
答案 0 :(得分:1)
使用
运行文件$ rails runner fileParser.rb
答案 1 :(得分:1)
rails app中这样的代码的常见做法是将代码放入custom rake task。如果您依赖于以下任务:环境任务,请执行以下操作:
namespace :performance do
desc 'print all performance file names'
task :print => :environment do
Performance.all.each {|perf| puts perf.file_name}
end
end
它将允许您使用应用程序的模型层。而且你将能够通过
运行这项任务rake performance:print
命令。