Rails Ruport using SQL - mysql

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

Related

SQLAlchemy - Unable to reflect SQL view

I'm getting the following error message when trying to reflect any of my SQL views:
sqlalchemy/dialects/mysql/reflection.py", line 306, in _describe_to_create
buffer.append(" ".join(line))
TypeError: sequence item 2: expected str instance, bytes found
I have tried using both the autoload_with and autoload=True options in my select query constructor to no avail.
I have the appropriate permissions on my view. My query is pretty simple:
company_country = Table('company_country', metadata, autoload_with=engine)
query = select(company_country.c.country)
return query
I've tried the inspect utility and it does not list my SQL view, nor does the reflecting all tables described below the views section on this page: https://docs.sqlalchemy.org/en/14/core/reflection.html#reflecting-views
I'm using version SQLAlchemy->1.4.32, Python 3.x and mySQL 8.0.28 on Mac if that's any help
I should add that I can query my SQL views using the text() constructor but it would be far more preferable to use select() if possible.
Any tips appreciated
I was using the mysql-connector client for interop with other code, but after switching to the mysqlclient, I was able to reflect the views.
https://docs.sqlalchemy.org/en/14/dialects/mysql.html#module-sqlalchemy.dialects.mysql.mysqldb

How would this rails query be on sql query?

I'm trying to run something like this directly on mysql server database:
SupportRequest.all.map{ |support_request| SupportRequestFeedback.create(support_request_id: support_request.id) if support_request.support_request_feedback == nil}
I know the query it produces but not how to implemented in a 1 query command (with the loop)?
You can enter this line in rails console to display queries:
ActiveRecord::Base.logger = Logger.new(STDOUT)
Then enter your code and the query will be displayed.
I may be wrong, but I don't think Rails provides a call to do this kind of operation at once.
You can setup a service to perform this for you, though:
support_requests_without_feedback = SupportRequest.includes(:support_request_feedback).where(support_request_feedback: {id: nil})
You could use the active_record-import gem to achieve mass db insert or you could use this: (not so effecient, though):
support_requests_without_feedback.map{|sr| sr.support_request_feedback.create }

Rails - Model Validations doesn't apply on mysql insert/update command

For the reason, I've used mysql cmd insert into table_name (....) update custom_reports ...and hence I miss out on Model validations
validates_uniqueness_of :name
validates_presence_of :name, :description
How to validate now in rails way? Or, use the mysql way to validate(needs help in this way too)?
Rails validation and other ActiveRecord and ActiveModel magic don't work if you only execute custom SQL command. None of your model classes is even instantized then.
For Mysql (or any sql like DB), you can modify the column attribute to:
Unique (this would validate uniqueness)
Not null (this would validate presence)
I know doing the above with OCI8 and oracle would result in exceptions which I am guessing should be same with ActiveRecord and Mysql, so you should be handling your exceptions correctly
But as #Marek as said you should be relying on Active record and be doing things like
Model.create()
OR
model_instance.save()
If you want to find (and perhaps handle) the entries in your db that are not valid, try the following in the rails console:
ModelName.find_each do |item|
unless item.valid?
puts "Item ##{item.id} is invalid"
# code to fix the problem...
end
end
valid? runs the Validations again, but does not alter the data.

Rails 3 active record observer not working when updating through MySQL command line/workbench

I'm working on ROR 3 app . I have added the following observer but I dont see any output as expected in the console or log file ( i have tried in both development and production modes)
cmd : rails g observer auditor
models:
class AuditorObserver < ActiveRecord::Observer
observe :excel_file
def after_update(excel_file)
excel_file.logger.info('New contact added!')
AuditTrail.new(execl_file, "UPDATED")
puts "*******************"
logger.info "********************************************"
end
end
application.rb:
config.active_record.observers = :auditor_observer
What am I missing in here? When I change the database (thru Mysql workbench/command line) I don't see any of the above lines getting executed.. neither after_update/after_save. But after_save works if I'm executing a query thru the app itself and do #excel.save
How else are we supposed to update data in DB so that we see the observer working????
When you bypass activerecord by modifying the database directly, you naturally bypass all of the activerecord callbacks.
So the answer is to update the data through the application, or to use database triggers instead.

Reconnect everytime to mysql with Grape

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.