2012-10-23 143 views
1

我试图设置使用在后端的ActiveRecord来处理所有的数据繁重的一个IRC bot内(可能是矫枉过正,但是这部分是我的一个学习经验:3)使用ActiveRecord另一个类

我正在运行的问题是,在定义我的数据库模式后,当我试图引用我创建的表时,在同一个脚本中,我从SQLite gem中得到一个错误,说它无法找到表。

而且,我的IDE(RubyMine的)抱怨说,它是“无法找到导轨型号:联想笔记场”

有个声音告诉我,如果我不是从作为操作的限制,这将不会发生僵尸框架的类,但这只是一个疯狂的猜测。

我在这里做错了什么?

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) 
+1

'Note'有很多'notes'? – oldergod

+0

是的,如果我理解这个权利,Note类就是我要调用的从我的数据库添加和删除笔记的内容,我使用上面创建的笔记表做这件事。班级笔记有很多笔记(数据库行) –

+1

'has_many'和cie。用于声明不同模型之间的关联。不在桌子和班级之间。例如,一个雇主'has_many':员工。这是两个不同表格的两种不同模型。你的情况不需要任何东西。 – oldergod

回答

1

此时应更换此

class Note < ActiveRecord::Base 
    has_many :notes 
end 

class Note < ActiveRecord::Base 
end 

的ActiveRecord的后代:: Base类表示表中单列,不是一张桌子。 所以要通过id找到一些注释,您只需要拨打Note.find(123),其中123是db表中注释记录的ID。

+0

这最终成为问题的一部分,另一部分是内存表中的不安(如下所示)。谢谢! –

0

感谢大家澄清使用has_many和语法,但我的问题最终成为使用内存表而不是磁盘上的一个。有一次,我改变了七号线说

:database => 'notes.db' 

,而不是

:database => ':memory:' 

,并移除了票据类的has_many声明(我曾尝试它没有这样做,并得到了不同的错误),一切正常: )

相关问题