I am a ruby beginner and I have a question about how to use mysql with grape.
Do I have to call Mysql.new() everytime I want to use my database or is there a better way to do this?
I tried to make the new in initialize of my class API < Grape::API but it doesn't seem to work...
Any suggestion?
EDIT: Here is some code of something i did and that works fine, but i would like to improve this by not connecting to sql everytime if possible:
class API < Grape::API
before do
header "Access-Control-Allow-Origin", "*"
#db_co = Mysql.new("localhost", "root", "toto", "youfight_userapp")
end
resource :users do
get :toto do
result = #db_co.query("SELECT username FROM users WHERE id = 104")
result.fetch_row
end
end
end
I would strongly recommend you to use some kind of ORM. We ran into a lot of issues when we were trying to write ours API the way you are yours and in the end we switched to ORM. We choose datamapper, but there are lots of other choices. For example sequel seems to be quite solid.
Related
I am working on a big project with a lot of forms using BDE and ODBC to connect to MySQL Database.
I can compile it in Delphi 2009 and it works fine.
When i compile it in Delphi 2010, nothing works because TQuery can not pass parameter values correctly.
Here is an example :
txtUsername.Text = 'Admin';
Query1.Close;
Query1.SQL.Text = 'Select Count(*) From Tbl_User where Username = :username';
Query1.ParamByName('username').AsString = txtUsername.Text;
Query.Open();
The SQL will be sent to MySQL , looks like this :
Select Count(*) From Tbl_User where Username = 'A'
Only first character of parameter will be sent to the server : 'A' instead of 'Admin'
But if i use
Query1.ParamByName('username').AsAnsiString , then
it will works fine and parameter will be sent completely:
Select Count(*) From Tbl_User where Username = 'Admin'
There are huge number of TQuery and TTable in project and its not possible to change all calls of AsString to AsAnsiString.
Is there any solution for this? any settings to make it working fine? probably by making it to use Ansi as default instead of Unicode?
I tried finding some setting in compiling option, and changing ODBC parameters but none of them worked.
Any help would be appreciated.
Thanks
I understand the pressure for quick and cheap solutions, but sometimes they will be quick and cheap only at the first moment, and then will turn (in a near future) into a monster problem with no solution at all.
So, for the first move, I recomend you to read a post on Regex Replace. Use this to replace all your .AsString by .AsAnsiString and quickly get you application running as expected again.
But donĀ“t get too comfortable with this, you have a long term work ahead of you. My suggestion to give your application a better design is:
Remove your datasets from your forms and put them in a DataModule, so you will not mix persistence and business code with presentation code;
Stop working with specific dataset on your business code, go for TClientDataset, which is better than any other dataset and will give you a better application design and complete database and middleware independence;
Create a new database layer, putting all the database and middleware specifics behind an interface, what will give you a incredible level of database abstraction.
This is a time consuming work, of course, so, not a quick and certainly not a cheap solution, but it will give you a lot of insights and improve your techniques. During the process, your application will evolve as never before.
I'm fairly new to RSpec and have been trying to create some tests for my website, on which a user can post a reservation to the website, which is then saved to our database. I've been trying, using Rspec and Capybara, to simulate a user posting a reservation to the website. We have an existing test database, and at the end of the Rspec test want the new reservation to be written to the database, and not removed at the end of the Rspec test.
One of two things happens when we run the code: either it "works" but the new reservation can't be found in the database, or we get this error:
Failure/Error: Unable to find matching line from backtrace
ActiveRecord::StatementInvalid:
Mysql2::Error: This connection is in use by: #<Thread:0x007fb421fd6218 sleep>: SELECT `users`.* FROM `users` WHERE `users`.`id` = 6 ORDER BY `users`.`id` ASC LIMIT 1
# ./app/controllers/application_controller.rb:95:in `pass_login_status_to_js'
# ./app/middleware/search_suggestions.rb:12:in `call'
Why would this be happening? I realize that Capybara isn't generally meant to be making permanent changes to a database; is there a different program/gem you recommend?
I currently have config.use_transactional_fixtures = false, and also have added the following on the recommendation of a few websites:
class ActiveRecord::Base
mattr_accessor :shared_connection
##shared_connection = nil
def self.connection
##shared_connection || retrieve_connection
end
end
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
To reiterate, I do want Capybara to be writing to my database (we use SQL). What can I do differently? Does it have something to do with database cleaner?
Yes, it has everything to do with database_cleaner. If you have it setup properly, it will clean your database between scenarios, to keep the tests isolated.
There are a few ways to do what you want:
You can explicitly tell database_cleaner not to clean certain tables between scenarios:
DatabaseCleaner.strategy = :transaction, {except: [:countries, :states]}
DatabaseCleaner.clean_with(:truncation, {except: [:countries, :states]})
You can add your code to a before(:each) or before(:all) block
You can add your data to one or many fixtures
There are only a few cases where you should share data between scenarios (ie. countries, states tables, which are good candidates for #3)
In any other case, I advise against sharing data between scenarios.
I perodicially need to access a mysql database, my primary data store is mongo, which I access with mongoid. I want to know the best way to manage connections to mysql (with the mysql2 gem - 0.2.7) without using active record.
I current do the following ...
# In config/initializers/mysql.rb
class MySqlConnection
def self.client
#client ||= Mysql2::Client.new(host: ENV['mysql_host'],
username: ENV['mysql_username'],
password: ENV['mysql_password'],
database: ENV['mysql_database'])
end
end
and then I use connection, like so ...
rows_q = "SELECT * FROM amaizng_table WHERE great_column = '#{cool_value}' "
rows = ::MySqlConnection.client.query(rows_q)
And everything is working okay -- but I have a sneaking suspicion that I am doing something horribly wrong, and things are going to explode down the road.
Also Note, the application is hosted on heroku
Anyone know the best way to approach this?
Thanks!
Jonathan
why, just WHY would you get rid of ActiveRecord's awesomeness (or any other ORM, really) ?
class Amazing < ActiveRecord::Base
establish_connection :mysql_database
end
so simple it hurts. See this for more details.
Guys I'm using Ruport gem for Ruby Reporting, I gone through basic coding and configuration as follows
class Project < ActiveRecord::Base
acts_as_reportable
end
and in IRB console i tried as follows
irb(main):001:0> puts Project.report_table
and it's working fine to me.
Problem is instead of Model, how to write my own queries with SQL and add that to Ruport table object?
Finally I got this in Ruport API
So, Instead of using Model directly for reporting like this
irb(main):001:0> puts Project.report_table
We can write our SQL queries to model like this,
irb(main):001:0> puts Project.report_table_by_sql("SELECT * FROM projects")
what I need was this syntax
report_table_by_sql
We are using Sinatra and Sequel for a small API implementation. The problem we have however is that on every page request Sequel opens new connections to MySQL, and keeps them open till they timeout, or you restart Apache.
There's not a lot of documentation on how to reuse connections, so any help, explanations, and/or pointers in the right direction would help.
I wrapped the Sequel stuff in a tiny wrapper and reuse this wrapper, like this:
get '/api/:call' do
##api ||= SApi.new
##api.call(params[:call])
end
class SApi
def initialize
connect
end
def connect
#con = Sequel.connect("...")
end
def call(x)
#handle call using #con
end
end
Alternatively, you can call #con.disconnect once you're finished or call Sequel.connect using a block:
Sequel.connect("...") do |c|
# work with c
end #connection closed
We figured out what we were doing wrong. It was rather stupid, we initialized Sequel in a before filter in Sinatra.
So instead we do:
DB = Sequel.mysql("...")
Then we simply use the DB constant to use Sequel.