Raven
Raven

Reputation: 31

ActiveRecord and sqlite3 : find does not accept any condition?

I have a problem I can't figure out here. I'm writing a ruby script that deals with an sqllite database.

require 'rubygems'
require 'sqlite3'
require 'active_record'


ActiveRecord::Base.establish_connection(
    :adapter => "sqlite3",
    :database  => "../database/my.db"
)

class KeyWord < ActiveRecord::Base
    set_table_name "keywords"
end

# THIS STATEMENT WORKS (finds the first record, returns "ruby") :    
KeyWord.find(1).keyval


# THOSE STATEMENTS RETURN NO RESULT :      
KeyWord.find(:all, :conditions => {:keyval => "ruby"})

KeyWord.find_by_sql("SELECT * FROM keywords WHERE keyval='ruby'")

KeyWord.find_by_keyval("ruby")

This is how the table was created :

create_table :keywords do |table|
    table.column :keyval, :text
end

Does anyone know where this could come from ?

Thanks,

R.

Upvotes: 3

Views: 272

Answers (1)

Mario Olivio Flores
Mario Olivio Flores

Reputation: 2795

I see a couple of issues here.

  • I'm not sure why you're manually setting your table name. ActiveRecord assumes that your model name is camelCased. So... AR would, by default, search for a table called key_words. Why not just go with that?
  • Pay attention to which version of active record you are using. Passing in conditions is deprecated. You should be using the .where syntax. So... you would need to do KeyWord.where(:keyval => 'ruby').first or end in .all for a collection of results.
  • If you are just fooling around, you can use sqlite3 in memory. ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:")
  • Also don't forget to define your schema!

Here is full code w/ more modern syntax.

require 'rubygems'
require 'sqlite3'
require 'active_record'


ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" )

ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define(version: 2) do
  create_table :key_words do |t|
    t.text   :keyval
  end
end

class KeyWord < ActiveRecord::Base
end

Keyword.create!(:keyval => 'ruby')

# THESE STATEMENTS WORK:
KeyWord.find(1).keyval
KeyWord.where(:keyval => 'ruby').first 
KeyWord.where(:keyval => 'ruby').all
KeyWord.find_by_sql("SELECT * FROM key_words WHERE keyval='ruby'")
KeyWord.find_by_keyval("ruby")

Upvotes: 1

Related Questions