I just installed the "Sequel" gem. I know that there are a lot of methods that make SQL easier, but I think that's just confusing.
Is there a way to send a raw SQL query so that:
table.all
would be?
"SELECT * FROM table"
I just installed the "Sequel" gem. I know that there are a lot of methods that make SQL easier, but I think that's just confusing.
Is there a way to send a raw SQL query so that:
table.all
would be?
"SELECT * FROM table"
"You Can Just Use SQL" discusses how to embed SQL into Sequel expressions, but you're not going to take advantage of the power of an ORM if you do that. Instead, I'd recommend reading and playing with the examples in the "Cheat Sheet".
Here's a tweaked example from the README:
require 'sequel'
DB = Sequel.sqlite
DB.create_table :items do
primary_key :id
String :name
Float :price
end
items = DB[:items]
items.insert(:name => 'abc', :price => rand * 100)
items.insert(:name => 'def', :price => rand * 100)
items.insert(:name => 'ghi', :price => rand * 100)
At this point, an in-memory SQLite DB would exist and would contain rows.
The base query of items
is a select:
items.sql # => "SELECT * FROM `items`"
If we inspect the variable we get:
items # => #<Sequel::SQLite::Dataset: "SELECT * FROM `items`">
again showing the query.
The all
method runs the query and returns the result:
items.all # => [{:id=>1, :name=>"abc", :price=>41.416988254871455}, {:id=>2, :name=>"def", :price=>40.44638070518766}, {:id=>3, :name=>"ghi", :price=>65.1898528586475}]
The same could be done using:
DB["select * from items"] # => #<Sequel::SQLite::Dataset: "select * from items">
and, again, all
will retrieve the information from the DB and return it:
DB["select * from items"].all # => [{:id=>1, :name=>"abc", :price=>33.294219608356926}, {:id=>2, :name=>"def", :price=>29.25412438270755}, {:id=>3, :name=>"ghi", :price=>6.19681273957694}]
The doesn't begin to show the power of an ORM like Sequel though. Work through the README and then play with the examples in the Cheat Sheet and it'll make more sense.