【问题标题】:Using ActiveRecord inside another class在另一个类中使用 ActiveRecord
【发布时间】:2012-10-23 05:17:49
【问题描述】:

我正在尝试在后端使用 ActiveRecord 设置一个 IRC 机器人来处理所有繁重的数据(可能有点矫枉过正,但这部分是我的学习经历:3)

我遇到的问题是,在定义我的数据库架构之后,稍后在同一个脚本中,当我尝试引用我创建的表时,我从 SQLite gem 中收到一个错误,说它找不到桌子。

此外,我的 IDE (RubyMine) 抱怨它“无法找到 :notes 关联字段的 rails 模型”

有些事情告诉我,如果我不被限制为作为机器人框架的一个类运行,这将不会发生,但目前这只是一个疯狂的猜测。

我在这里做错了什么?

require 'cinch'
  require 'active_record'
  puts 'Memobox loaded'
  class Memobox
    include Cinch::Plugin
    ActiveRecord::Base.establish_connection(
        :adapter => 'sqlite3',
        :database => ':memory:'
    )
    ActiveRecord::Schema.define do
      create_table :notes do |table|
        table.column :id, :integer
        table.column :timeset, :DateTime
        table.column :sender, :string
        table.column :recipient, :string
        table.column :text, :string
      end
    end

  class Note < ActiveRecord::Base
     has_many :notes
  end

   match(/note.*/, :prefix => "?")
   def execute(m)
    Memobox::Note.create(
        :timeset => (Time.new).ctime,
        :sender  => m.user.nick,
        :text => m.message,
        :recipient => (m.message).split("_").at(1)
        )

   end
  end

错误:

 C:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/sqlite_adapter.rb:472:in `table_structure': Could not find table 'notes' (ActiveRecord::StatementInvalid)

【问题讨论】:

  • 是的,如果我理解正确的话,我将调用 Note 类从我的数据库中添加和删除笔记,我使用上面创建的 notes 表来执行此操作。课堂笔记有很多笔记(数据库行)
  • has_many 和 cie。用于声明不同模型之间的关联。不在桌子和班级之间。例如,一位雇主has_many :employees。这是两个不同表的两个不同模型。你不需要任何东西。

标签: ruby activerecord cinch


【解决方案1】:

你应该替换这个

class Note < ActiveRecord::Base
  has_many :notes
end

class Note < ActiveRecord::Base
end

ActiveRecord::Base 类的后代表示表中的单行,而不是整个表。 因此,要通过 id 查找一些便笺,您只需调用Note.find(123),其中 123 是 db 表中便笺记录的 id。

【讨论】:

  • 这最终成为问题的一部分,另一部分是内存表的 jankyness(如下所示)。谢谢!
【解决方案2】:

感谢大家对 has_many 的使用和语法的澄清,但我的问题最终是使用内存表而不是磁盘表。有一次我把第七行改成说

:database => 'notes.db'

而不是

:database => ':memory:'

并从 Notes 类中删除了 has_many 声明(我确实尝试过但没有这样做,但得到了一个不同的错误),一切正常 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多