Rails: Selecting from multiple tables using .join() - mysql

Plugins Model:
class Plugin < ActiveRecord::Base
belongs_to :report
has_many :vulns
end
Vulns Model:
class Vuln < ActiveRecord::Base
belongs_to :plugins
end
I'm doing the following in rails:
#using * for now to select everything
#data = Plugin.select("*").joins(:vulns).where('plugins.id'=> plugin.plugin_id)
Which does the following query in the terminal:
SELECT * FROM `plugins` INNER JOIN `vulns` ON `vulns`.`plugin_id` = `plugins`.`id` WHERE `plugins`.`id` = 186
It's the right query but it doesn't select the content from the vulns table. I know it's the right query because I tried it in phpmyadmin and it returned the data on the vulns table too. When I do it in rails (using <%= debug(#data) %>) it only shows content from the plugins table.
How do I make it select everything from the vulns table too? (Each plugin has multiple vulns)

Apparently you can't have a column with the name "type".
If anybody has similar issues, rename the column called "type". I generated a new migration:
rails g migration RenameColumnOnVulnsTable
And then added the following:
def change
rename_column :vulns, :type, :vulnerability_type
end
The query works fine now.

Related

Rails 5 HABTM from multiple databases works in mysql command but error in Rails

I am building an rails 5 app that connects to 2 different databases (dbA & dbB). My databases are on the same database host.
I want to make a wishlist. Pretty easy when using the same DB, but I am stuck with an "interesting" error.
This is what the databases look like:
the models are as follow:
user.rb
class User < ApplicationRecord
has_one :wishlist, dependent: :destroy
end
wishlist.rb
class Wishlist < ApplicationRecord
belongs_to :user
# has_and_belongs_to_many :wines
# The above did not work
# so I had to revert to has_many through
has_many :wines_wishlists
has_many :wines, through: :wines_wishlists
end
wines_wishlist.rb
class WinesWishlist < ApplicationRecord
belongs_to :wine
belongs_to :wishlist
def self.table_name_prefix
"dbA_#{Rails.env}."
end
# I added the above to prevent ActiveRecord from
# looking for the table in the wrong database
end
wine.rb (legacy model)
class Wine < ApplicationRecord
self.abstract_class = true
establish_connection LEGACY_DB
# LEGACY_DB is the legacy database connection info from a yaml file
# located in config.
def self.table_name_prefix
"dbB_#{Rails.env}."
end
end
This is quite straigth forward IMHO. Now the interresting error:
When I try the following :
user = User.last
user.wishlist.wines
It works on my local machine in development. It doesn't work on my staging server! When I try in the rails console, I get this:
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'dbA_staging.wines_wishlists' doesn't exist: SELECT `dbB_staging`.`wines`.* FROM `dbB_staging`.`wines` INNER JOIN `dbA_staging`.`wines_wishlists` ON `dbB_staging`.`wines`.`id` = `dbA_staging`.`wines_wishlists`.`wine_id` WHERE `dbA_staging`.`wines_wishlists`.`wishlist_id` = 1
This is the expected SQL.
user.wishlist.wines.to_sql
=> "SELECT `dbB_staging`.`wines`.* FROM `dbB_staging`.`wines` INNER JOIN `dbA_staging`.`wines_wishlists` ON `dbB_staging`.`wines`.`id` = `dbA_staging`.`wines_wishlists`.`wine_id` WHERE `dbA_staging`.`wines_wishlists`.`wishlist_id` = 1"
Even better, when I try the same SQL in rails db on my staging machine, it works!! It doesn't work in rails even though the SQL is correct, but it works in mysql command line.
I based my code on the following article and made some research, but I can't seem to figure out how to go around this problem.
I am using (same for development and staging):
Rails 5.1.1
ruby 2.4.0p0
mysql 5.6.34 (staging)
mysql 5.7.17 (development)
Any help would be greatly appreciated!
Taking a look at the article you linked to, it seems to be using a gem st-elsewhere, i.e.
has_many_elsewhere :wines, :through => :wines_wishlist
Also, as stated in the article, you can't make JOIN queries across database connections. The gem circumvents this using some less efficient queries, the details of which I did not look up.

Ruby on Rails: "SELECT" MySQL command

I'm writing an application using MySQL. There's a table called "Requests".
That table has a field "user_id" from Table "Users".
I'd like to select all requests from a user_id.
For example:
SELECT * FROM requests WHERE user_id = ("the id I want");
How can I do that using Ruby language, and not an SQL string?
In ActiveRecords its done like this:
Request.where(user_id: ID)
Request.find_by_user_id(USER-ID-YOU-WANT)
Or
Request.find_by user_id: 'USER-ID-YOU-WANT'
documentation here
There are a few different ways, as you can see from #shivam and #amalrik's answers. It also depends on the ORM you're using. If you're using Rails out of the box, you're probably using ActiveRecord.
Probably the most idiomatic way is to have the correct associations on your User and Request models.
in app/models/user.rb:
class User < ActiveRecord::Base
has_many :requests
end
and app/models/request.rb:
class Request < ActiveRecord::Base
belongs_to :user
end
This would allow you to find a user and call its #requests method:
User.find(user_id).requests

Forming of SQL query in Rails Application

I am new to Ruby on Rails. Now I am working on performance issues of a Rails application. I am using New Relic rpm to find out the bottlenecks of the code. While doing this I find something that I cannot figure out. The problem is that here in my Rails application I have used two models A, B and C where model B has two properties: primary key of A and primary key of C like following:
class B
include DataMapper::Resource
belongs_to :A, :key=>true
belongs_to :C, :key=>true
end
Model of A is as follows:
class A
include DataMapper::Resource
property :prop1
...
has n, :bs
has n, :cs, :through => :bs
end
While issuing the following statement a.find(:c.id=>10) then internally it is executing the following SQL query:
select a.prop1, a.prop2,... from a INNER JOIN b on a.id = b.a_id INNER JOIN c on b.c_id = c.id where (c.id=10) GROUP BY a.prop1, a.prop2,....[here in group by all the properties that has been mentioned in select appears, I don't know why]
And this statement is taking too much time during web transaction. Interesting thing is that, when I am executing the same auto generated query in mysql prompt of my terminal it's taking very less amount of time. I think it's because of mentioning so many fields in group by clause. I cannot understand how the query is being formed. If anyone kindly help me to figure this out and optimize this, I will be really grateful. Thank you.
I assume you have you model associations properly configured, something like this:
class A < ActiveRecord
has_many :B
has_many :C, through: :B
end
class B < ActiveRecord
belongs_to :A
belongs_to :C
end
class C < ActiveRecord
has_many :B
has_many :A, through: :B
end
then you could simply call:
a.c.find(10) #mind the plural forms though
You will get better performance this way.

Rails database query - is it possible to give a column an alias?

I've got to produce a json feed for an old mobile phone app and some of the labels need to be different from my database column names.
I think the most efficient way of doing this would be to do a create an alias at the database level. So I'm doing things like
Site.where( mobile_visible: true ).select("non_clashing_id AS clientID")
which produces the SQL
SELECT non_clashing_id AS clientID FROM `sites` WHERE `sites`.`mobile_visible` = 1 ORDER BY site_name
If I run this query in MYSQL workbench it produces a column with the heading ClientID as I expect, with the required values.
But if I show the object in a rails view I get {"clientID":null},{"clientID":null},{"clientID":null}
What am I doing wrong? Is there a better way of doing this?
This shows how to access the variable
sites = Site.where( mobile_visible: true ).select("non_clashing_id AS clientID")
sites.each do |site|
puts site.clientID
end
I think by default, activerecord loads column definitions from the database. And, it should load value into existing columns only.
Site.columns
I guess you could add one more item to that array. Or you could use the normal query without alias column name, then add alias_attribute like MurifoX did and overwrite as_json method:
class Site < ActiveRecord::Base
alias_attribute :client_id, :non_clashing_id
def as_json(options={})
options[:methods] = [:client_id]
options[:only] = [:client_id]
super
end
end
Try putting this in your model in addition to the database alias:
class model < ActiveRecord::Base
alias_attribute :non_clashing_id, :client_id
...
end

Rails query chokes on includes

This query executes just fine:
p = PlayersToTeam.select("id").joins(:player).limit(10).order("players.FirstName")
This query causes my whole system to come to a screeching halt:
p = PlayersToTeam.select("id").includes(:player).limit(10).order("players.FirstName")
Here are the models:
class PlayersToTeam < ActiveRecord::Base
belongs_to :player
belongs_to :team
accepts_nested_attributes_for :player
end
class Player < ActiveRecord::Base
has_many :players_to_teams
has_many :teams, through: :players_to_teams
end
As far as I can tell, the includes does a LEFT JOIN and joins does an INNER JOIN. The query spit out (for joins) from Rails is:
SELECT players_to_teams.id FROM `players_to_teams` INNER JOIN `players` ON `players`.`id` = `players_to_teams`.`player_id` ORDER BY players.FirstName LIMIT 10
Which executes just fine on the command line.
SELECT players_to_teams.id FROM `players_to_teams` LEFT JOIN `players` ON `players`.`id` = `players_to_teams`.`player_id` ORDER BY players.FirstName LIMIT 10
also executes just fine, it just takes twice as long.
Is there an efficient way I can sort the players_to_teams records via players? I have an index on FirstName for players.
EDIT
Turns out the query required heavy optimization to run even half decently. Splitting the query was the best solution short of restructuring the Data or customizing the query
You also might consider to split it into 2(3) queries. First - to get ids by sorting with joins:
players_to_teams = PlayersToTeam.select("id").joins(:player).limit(10).order("players.FirstName")
Second (which is inside contains 2 queries) - to get PlayersToTeams with players pre-loaded.
players_to_teams = PlayersToTeam.include(:player).where(:id => players_to_teams.map(&:id))
So after that you will have fully initialized players_to_teams with players loaded and initialized.
One thing to note is that include will add a second db access to do the preloading. You should check what that one looks like (it should contain a big IN statement on the player_ids from players_to_teams).
As for how to avoid using include, if you just need the name from players, you can do it like this:
PlayersToTeam.select("players_to_teams.id, players.FirstName AS player_name").joins(:player).limit(10).order("players.FirstName")