bobby-tables icon indicating copy to clipboard operation
bobby-tables copied to clipboard

Ruby page is a bit out of date

Open andy-twosticks opened this issue 9 years ago • 5 comments

Ruby/DBI appears to be long gone. Some alternatives:

Sequel

http://sequel.jeremyevans.net/

DB["update customer where code = ?", "abc1"].update
DB.fetch("select * from customer where code = ?", "abc1")

RDBI

https://github.com/RDBI/rdbi

dbh.prepare("insert into tbl (string, number) values (?, ?)") do |sth|
  sth.execute("quux", 1024)
end

andy-twosticks avatar Nov 10 '16 17:11 andy-twosticks

Thanks for that. Can you add any more text about either of those? I don't know Ruby at all.

petdance avatar Nov 10 '16 17:11 petdance

Okay then, lets leave out RDBI. I know little about it and between ActiveRecord and Sequel we pretty much have it covered (unfortunately...)

Feel free to edit/ignore as you please:


Using ActiveRecord

ActiveRecord is the default when using Ruby On Rails.

Once you have defined a model for your table -- say, customer -- you can then query it with parameters like this:

Customer.where("cust_code = ? and status = ?", my_code, 'active')

or

Customer.where( "cust_code = :code and status = :status", {code: my_code, status: 'active'} )

Using Sequel

The simplest approach: for a query that returns results, use DB.fetch:

DB.fetch("select * from customer where code = ?", my_code)

For an update, delete or insert, build the query with DB[] and then call the corresponding function to execute it:

DB["update customer where code = ?", my_code].update

More information here and here.

Notes

The secureness of the above depends on how well the underlying database supports parameter substitution, but it's always better to do it than not.

If you are using an ORM and not passing it an SQL string, then you are probably already protected by the ORM.

andy-twosticks avatar Nov 11 '16 09:11 andy-twosticks

Thank you for this.

petdance avatar Nov 11 '16 14:11 petdance

Happy to help -- no problem.

andy-twosticks avatar Nov 14 '16 10:11 andy-twosticks

Sorry for necro-posting (though the issue is not closed still) and offtopic, but could some Ruby+SQL guru look at https://stackoverflow.com/questions/53500616/ ?

the-Arioch avatar Nov 28 '18 15:11 the-Arioch