sinatra-sequel
sinatra-sequel copied to clipboard
`db': No database associated with Sequel::Model (Sequel::Error)
When I use a Sinatra::Base class to create my App like for example: myapp.rb
require 'sinatra/base'
require 'sinatra/sequel'
class MyApp < Sinatra::Base
configure do
set :sessions, true
set :database, "postgres://username:password@localhost/mydb"
require 'article.rb'
end
get '/' do
'Hello world!'
end
end
article.rb class Article < Sequel::Model end
wherever I put the require line of my model, this error occurs: 'db': No database associated with Sequel::Model (Sequel::Error)
My goal is to use this model not only in MyApp class but also in another classes instantiated in place of the "hello world" line (so in a get path block).
Same thing here...once I went < Sinatra::Base I got the same message.
configure do
set :database, "postgres://username:password@localhost/mydb"
end
Should instead be
configure do |m|
m.database = "postgres://username:password@localhost/mydb"
end
See if that fixes it.
Tried both ways and didn't get it to work. @rstacruz said got me the following error
block in <class:App>': undefined local variable or methodm' for App:Class (NameError)
Try loading models with autoload to ensure that a db connection has been set up before the models are loaded:
class App < Sinatra::Base
autoload :Article, 'lib/article'
configure do
set :database, "postgres://username:password@localhost/mydb"
end
end
I got this same error when I first added Sequel::Models to the application I'm working on.
Have you checked that you require files in the correct order?
I got it to work, sorry for not saying earlier how I did it. I got it to work by moving database configuration to the class body and setting DB. Don't know if it's the right way to do it but it worked.
require 'sinatra'
require 'sinatra/sequel'
class App < Sinatra::Base
set :database, "mysql2://user:pass@#host/db"
DB = Sequel.connect(settings.database)
...
end
I told myself not to write off sinatra and sinatra-sequel just because they weren't under active development, but man, reading this thread from 2010 and seeing that the correct solution hasn't yet been given... not good. Maybe I should use Node.js or something for my API instead. Where's the maintainer?!
Anyway, in order to use sinatra-sequel in a modular Sinatra application, you have to add this line into your class:
require 'sinatra/base'
require 'sinatra/sequel'
class App < Sinatra::Base
register Sinatra::SequelExtension # this one
configure do
set :database, 'sqlite://app.db'
end
# now the `database' method is available to use per the README
end
Sequel will try to fire up the database as soon as you subclass Sequel::Model so there's a bit of a race condition here; you need to set :database in a configure block before that happens. Autoload your models per @troelskn's suggestion and add the register line and it will work fine. Hope this helps someone in the future...