How to display results from database in Sinatra using Sequel? - ruby

I have an SQLite3 database called sk.db with a table called Sked that displays a schedule of sports matches with a column date. I am simply trying to display today's matches. It appears as though the connection to the database is not working, though I do not get any errors.
I have tried looking through the Sequel documentation to no avail. How can I display results from an existing database in Sinatra?
.rb
require 'date'
require 'sequel'
require 'sinatra'
DB = Sequel.connect("sqlite://sk.db")
class Sked < Sequel::Model
end
schedule = DB.from(:sked)
get '/' do
todaymatches = schedule.where(:date => Date.today)
erb :games
end
.erb
<h1>Games</h1>
<p><%= #todaymatches %></p>

.where doesn't actually retrieve data, but instead returns a dataset. Add an .all to actually retrieve the data
todaymatches = schedule.where(:date => Date.today).all

Related

Can I change SQLite column name with DataMapper?

Brand new to DataMapper and wondering if I can use DataMapper.auto_updgrade! to change a column name of an existing column in a SQLite database?
If I have the following in a song.rb
require 'date'
require 'dm-core'
require 'dm-migrations'
DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/development.db")
class Song
include DataMapper::Resource
property :id, Serial
property :title, String
property :music_by, String
property :lryics_by, String
property :lyrics, Text
property :length, Integer
property :released_on, Date
def released_on=date
super Date.strptime(date, '%m/%d/%Y')
end
end
DataMapper.finalize
After a Song.auto_migrate!
2.0.0-p598 :004 > Song.new
=> #<Song #id=nil #title=nil #music_by=nil #lyrics_by=nil #lyrics=nil #length=nil #released_on=nil>
Is it possible to change the
property :lryics_by, String
to
property :words_by, String
and have the database column name change, but keep any existing data?
I've tried with Song.auto_upgrade! and it adds an empty new column and leaves the original column and data in place. On the other hand, my Song.new object looks right.
2.0.0-p598 :004 > Song.new
=> #<Song #id=nil #title=nil #music_by=nil #words_by=nil #lyrics=nil #length=nil #released_on=nil>
It seems like I need a migration in the way that ActiveRecord (I've played around a little with that ORM) handles migrations. Or I would need to change the column name with SQL or an app or the Firefox SQLlite plugin.
UPDATE:
I'm wondering now if this is more a SQLite thing than a DataMapper thing. When I went to delete a column in Firefox's SQLite Manager plugin I got this message:
This is a potentially dangerous operation. SQLite does not support statements that can alter a column in a table. Here, we attempt to reconstruct the new CREATE SQL statement by looking at the pragma table_info which does not contain complete information about the structure of the existing table.
Do you still want to proceed?
dm-migrations can do this but not for SQLite, mostly because SQLite doesn't support renaming columns, as it has a limited ALTER TABLE implementation (http://www.sqlite.org/lang_altertable.html)
There's a rename_column migration but as you can see from the dm-migrations TableModifier class (https://github.com/datamapper/dm-migrations/blob/master/lib/dm-migrations/sql/table_modifier.rb), it's not available for SQLite:
def rename_column(name, new_name, opts = {})
# raise NotImplemented for SQLite3
#statements << #adapter.rename_column_type_statement(table_name, name, new_name)
end

Retrieving rows from in sequel gem

i am trying to retrieve a row from a dataset
my model class is
require 'sequel'
class Item < Sequel::Model
end
and one my hello.rb file is
require "rubygems"
require './post'
require "sequel"
require './item'
# connect to an in-memory database
#DB = Sequel.connect('postgres://ritesh:newpassword#localhost')
puts Item.filter(:id =>'1').first
its giving me output
#<Item:0xb693996c>
i want to get all the columns of the row whose id field is 1 what should be the query??
try
puts Item.filter(:id =>'1').first.inspect
or
puts Item.filter(:id =>'1').first.to_yaml
(for better formatting if you have yaml required in your code like so require 'yaml')

In Ruby/Sinatra, Datamapper's .all works but .get doesn't?

I am trying to take data from a path in Sinatra, and use it to look up a particular record using Datamapper. The Datamapper docs seem to indicate that.
get "/test/:test_path" do
test_get = Intake.get( params[:test_path] )
# Do stuff
erb :blah_blah_blah
end
should find any records associated with the symbol :test_path
This does not work. test_get gets nil.
Meanwhile, what does work is
get "/test/:test_path" do
test_all = Intake.all(:test_path => params[:test_path] )
# Do stuff
erb :blah_blah
end
My two questions are:
What am I doing wrong with the .get() call in Datamapper?
Is the .all(:name => value) method slower than .get(), or does it not matter which I use?
Here's a Sinatra script pared down to demonstrate the behavior.
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
require 'dm-core'
require 'dm-timestamps'
DataMapper.setup(:default, {:adapter => 'yaml', :path => 'db'})
class Intake
include DataMapper::Resource
property :id, Serial
property :created_at, DateTime
property :test_path, String
end
get "/test/:test_path" do
test_all = Intake.all(:test_path => params[:test_path] )
puts 'test_all:' test_all.inspect
test_get = Intake.get( params[:test_path] )
puts 'test_get:' test_get.inspect
"Hello World!"
end
#get only does a lookup based on primary key, with is the id. So
Intake.get(params[:test_path])
looks for something with id params[:test_path], which will fail. Use
Intake.first(test_path: params[:test_path])

MongoMapper save not working

No idea why this is not working. It's the first time I am working with Mongo, but from all the docs I have read, this should work? Anyone have any idea what I am missing?
require 'rubygems'
require 'sinatra/base'
require 'mongo_mapper'
mongo_server = '127.0.0.1'
mongo_database = 'inone'
MongoMapper.connection = Mongo::Connection.new(mongo_server)
MongoMapper.database = mongo_database
# DB model
class URLstore
include MongoMapper::Document
key :url_key, String
key :url, String
end
class URLnip < Sinatra::Base
get '/testmongo' do
nipurl = URLstore.new(:url_key => "abc", :url => "www.google.com")
nipurl.save
end
end
Opening the Mongo terminal I can see the DB get's created
> show dbs
inone 0.203125GB
but doing this brings back no results at all
> db.inone.find()
>
or
> db.inone.find({url : 'www.google.com'})
>
same thing nothing.
Shouldn't that be db.urlstore.find()? Or however MongoMapper changes the case. What does show collections in a Mongo shell say after you select the right database?

uninitialized constant ActiveRecord::RecordNotUnique

I am using rails 2.3.4, rubygems 1.3.6, activerecord 3.1.0, windows 7 home basic
Here's my code:
def items
#products = ShopifyAPI::Product.find(:all)
#products.each do |a|
begin
#shop = Product.new(:title => a.title , :shop_id => a.id, :product_type => a.product_type)
#shop.save
rescue ActiveRecord::RecordNotUnique
redirect_to :action => "display_items"
end
end
#shop_items =Product.find(:all)
if session[:user_id]
#log = "Welcome Administrator!"
#logout="logout"
else
#log = "Admin Log in"
#logout=""
end
end
I'm having the error "uninitialized constant ActiveRecord::RecordNotUnique" when trying to save the data fed by the API. Any help would be appreciated. thank you.
Any reason why you use ActiveRecord 3.1 with Rails 2.3.4. Though it's possible to use that, it is not recommended.
ActiveRecord::RecordNotUnique is only available with versions 3.0 or higher. I am not sure if activerecord modules are initialized correctly with your version of Rails.
That error is returned when ActiveRecord tries to save a duplicate when the index says values need to be unique. In your case, the value Baby Ruth-49696852 is a duplication, and violates the uni_products key, which is set to be unique.
Either make the column not unique, or stop trying to save duplicate records. Did you create your database indexes in your migrations? Is there a :unique => true on any of the columns in your migrations?

Resources