Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ruby page is a bit out of date #66

Open
andy-twosticks opened this issue Nov 10, 2016 · 5 comments
Open

Ruby page is a bit out of date #66

andy-twosticks opened this issue Nov 10, 2016 · 5 comments

Comments

@andy-twosticks
Copy link

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
@petdance
Copy link
Owner

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

@andy-twosticks
Copy link
Author

andy-twosticks commented Nov 11, 2016

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.

@petdance
Copy link
Owner

Thank you for this.

@andy-twosticks
Copy link
Author

Happy to help -- no problem.

@the-Arioch
Copy link

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/ ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants