1

我正在尝试在后端使用 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)
4

2 回答 2

1

你应该替换这个

class Note < ActiveRecord::Base
  has_many :notes
end

class Note < ActiveRecord::Base
end

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

于 2012-10-23T07:42:24.430 回答
0

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

:database => 'notes.db'

代替

:database => ':memory:'

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

于 2012-10-23T19:29:35.453 回答