【问题标题】:Access a model from a Ruby file in Rails?从 Rails 中的 Ruby 文件访问模型?
【发布时间】: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


【解决方案1】:

运行文件使用

$ rails runner fileParser.rb

【讨论】:

  • 它有效。当您刚接触 Rails 时,很难跟踪所有事情。 (现在我还需要添加目录名称,因为我将文件放在 lib dir 中。所以我用rails runner lib/script.rb 运行了运行器。非常感谢。)
  • 没关系,但删除您之前添加的config.autoload_paths += %W(#{config.root}/lib) 以避免文件在重新启动rails时自动运行......我再次不确定这个“自动运行”的东西:D
【解决方案2】:

Rails 应用程序中此类代码的常见做法是将代码放入custom rake task。如果您将任务依赖于 :environment 任务,如下所示:

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 

命令。

【讨论】:

    猜你喜欢
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 2011-01-26
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多