문제

I'm trying to set up an IRC bot using ActiveRecord on the back end to handle all the data heavy lifting (probably overkill, but this is partly a learning experience for me :3)

The issue I'm running in to is that, after defining my database schema, later on in the same script when I try to reference the table I created, I get an error from the SQLite gem saying that it could not find the table.

Furthermore, my IDE (RubyMine) complains that it is "Unable to find the rails model for :notes association field"

Something tells me this would not be happening if I weren't constrained from operating as a class of the bot framework, but that is only a wild guess at this point.

What am I doing wrong here?

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

Error:

 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)
도움이 되었습니까?

해결책

You should replace this

class Note < ActiveRecord::Base
  has_many :notes
end

with

class Note < ActiveRecord::Base
end

The descendants of ActiveRecord::Base class represents single row in a table, not a whole table. So to find some note by id you need just to call Note.find(123), where 123 is the id of note record in db table.

다른 팁

Thanks to everyone for the clarification on the use of has_many and the syntax, but my problem ended up being the use of an in memory table instead of an on disk one. Once I changed line seven to say

:database => 'notes.db'

instead of

:database => ':memory:'

and removed the has_many declaration from the Notes class (I did try it without doing this and got a different error) , everything works :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top