[英]Using ActiveRecord inside another class
我正在嘗試使用后端的ActiveRecord設置IRC機器人來處理所有繁重的數據(可能過大了,但這對我來說部分是學習的經驗:3)
我遇到的問題是,在定義數據庫架構之后,稍后當我嘗試引用創建的表時,在同一腳本中,我從SQLite gem中收到一條錯誤消息,提示它找不到表。
此外,我的IDE(RubyMine)抱怨說“無法為:notes關聯字段找到rails模型”
有人告訴我,如果我不受限於作為bot框架的類來進行操作,則不會發生這種情況,但這只是一個瘋狂的猜測。
我在這里做錯了什么?
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)
你應該更換這個
class Note < ActiveRecord::Base
has_many :notes
end
同
class Note < ActiveRecord::Base
end
ActiveRecord :: Base類的后代表示表中的單個行,而不是整個表。 因此,要通過ID查找一些注釋,您只需調用Note.find(123)
,其中123是數據庫表中注釋記錄的ID。
感謝每個人對has_many和語法使用的澄清,但是我的問題最終是使用內存中表而不是磁盤上的表。 一旦我改變第七行說
:database => 'notes.db'
代替
:database => ':memory:'
並從Notes類中刪除了has_many聲明(我沒有這樣做就嘗試了它,並得到了另一個錯誤),一切正常:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.