Select everything in a database that == something OR something else - ruby-on-rails

I'm trying to select everything in a table where a column == "something" OR "somethingelse".
Is there a way of doing this without using raw SQL? Something like the following would be ideal.
Table.where(:col => "something" OR "somethingelse")

Table.where(:col => ["something", "somethingelse"])
should generate
SELECT * FROM table WHERE col IN ('something', 'somethingelse')

You can use:
MyModel.where("col1 = ? or col1 = ?", "something","somethingelse")

You can use the statement like this:
select * from table_name where column_name = value1 or column_name = value_2
You can also use:
select * from table_name where column_name in (value1,value2)

Related

Is it possible to get column names from joined tables?

I want to extract the table headers from JOINed tables to use as <th> in an MVC view instead of having to hard code them. Is it possible to do this using "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ..."?
What I have tried:
The normal query using only one table returns the colum names for one table successfully:
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbbiblio AND TABLE_NAME = 'book'";
This is the JOIN query for three tables which gives a syntax error:
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbbiblio' AND TABLE_NAME = 'book' JOIN 'author' ON 'book.author' = 'author.author_id' JOIN 'publisher' ON 'book.publisher_id' = 'publisher.publisher_id'";
I also attempted this unsuccessfully:
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbbiblioAND TABLE_NAME = 'book' AND TABLE_NAME = 'author' AND TABLE_NAME = 'publisher'";

Joining tables in activerecord based on a column of the first table

I want to accomplish a join like this:
MyModel.joins(:other_model).
where(column: 123, other_model { other_column: column_in_my_model })
In practice, this would be something like
SELECT * FROM my_model m
INNER JOIN other_model o on m.column = o.foreign_key
WHERE m.column = 123 AND o.other_column = m.column_in_my_model
In the activerecord version, there's no way to refer to column_in_my_model that I know of without passing an SQL string. Is it possible to do this with activerecord syntax without passing a raw SQL string? Arel is OK too.
You can do something like this
MyModel.joins(:other_model)
.where(my_model_column: 123)
.where('column_in_my_model = other_model_column')
MyModel.find(:all,
:joins=>" JOIN other_model_table_name ON other_model_table_name.column = my_models.column",
:conditions=>"my_models.column = '123' AND other_model_table_name.column = my_models.column"
)

NOT EXISTS SQL query in rails 3.2

I have an sql query like this:-
SELECT * FROM `permissions` join entities where NOT EXISTS (select
entity_id,permission_id from role_permissions where role_id=5 and
entities.id = role_permissions.entity_id and permissions.id =
role_permissions.permission_id)
I would like to get the corresponding rails query.
I have tried this.
Permission.joins("join entities").joins("LEFT OUTER JOIN role_permissions on
permission_id != permissions.id and entities.id != entity_id and
role_permissions.role_id= role_id").select("role_permissions.entity_id,role_permissions.role_id,
role_permissions.permission_id").group('role_permissions.entity_id,
role_permissions.permission_id')
But it doesn't works.
thanks
hari
I have been particularly in love with EXISTS queries lately, precisely because it does not require you to fully join another table. As far as I know, you do have to explicitly write the SQL clause, but you can still make it work with Activerecord. You can even put this in a scope within a lambda block.
Permission.joins(:entities).where(<<-SQL
NOT EXISTS(
select
* from role_permissions where role_id=#{your_role_id} and
entities.id = role_permissions.entity_id
and permissions.id = role_permissions.permission_id
)
SQL
)
Try like this for a default SQL query:
sql = "SELECT some_field FROM `permissions` join entities where NOT EXISTS (select entity_id,permission_id from role_permissions where role_id=5 and entities.id = role_permissions.entity_id and permissions.id = role_permissions.permission_id)"
results = ActiveRecord::Base.connection.execute(sql)
results.each do |result|
#register_users << { some_field: result[0] }
end
Try this
UPDATED BASED ON FIRST COMMENT
Permission.joins(:entities).joins("LEFT OUTER JOIN role_permissions on
permission_id != permissions.id and entities.id != entity_id and
role_permissions.role_id= role_id")
.select("role_permissions.entity_id,role_permissions.role_id,
role_permissions.permission_id")
.group('role_permissions.entity_id, role_permissions.permission_id')

how to convert sql query in ruby and rails?

SELECT A.FirstName, A.LastName, B.PatientId, B.RoomNumber, B.AdmissionDate, B.DischargeDate, B.MeasureCategory
FROM DimPatient A, DimPatientStay B
WHERE A.Id = B.PatientId AND A.FirstName = 'Anuj' AND B.MeasureCategory = 'ED'
hi some updation for this
i solved this prob by
MODELNAME.find_by_sql("your sql query")
You can try this to find the result from sql query in Rails
query_params = Hash.new
sql_query = "SELECT A.FirstName, A.LastName, B.PatientId, B.RoomNumber, B.AdmissionDate, B.DischargeDate, B.MeasureCategory
FROM DimPatient A, DimPatientStay B
WHERE A.Id = B.PatientId AND A.FirstName = :first_name AND B.MeasureCategory = :measure_category"
query_params[:first_name] = first_name
query_params[:measure_category] = measure_category
#query_results = ActiveRecord::Base.connection.select_all(
ActiveRecord::Base.send("sanitize_sql_array",[sql_query, query_params] )
)
I guess you could try:
ActiveRecord::Base.connection().execute(#your_sql_here)
Suppose A is one class and B is another, you should use includes as following:
A.includes(:b).where(...) # add you condition in where
I suggest to check good video tutorials of ActiveRecord here

psql excluding records base on another table

i am using postgres and wishing to exclude users that are currently in one table from another. at present i am trying do this via the ActiveRecord system within Rails.
So i need it to get the ids from my Availability table, then return that id into my User table to remove them if they are in the Availability table.
#availabilities = Availability.where(:event_id => params[:id]).all
#players = User.where('team_id = ? and id <> ?', current_user[:team_id], #availabilities).all
this is returning the following error
PG::Error: ERROR: argument of WHERE must be type boolean, not type record
LINE 1: SELECT "users".* FROM "users" WHERE (team_id = 1 and id <> ...
^
: SELECT "users".* FROM "users" WHERE (team_id = 1 and id <> 101,102,103)
changed code as mentioned below, though the way i am doing it is still probably not ideal
#availabilities = Availability.where(:event_id => params[:id]).all
#exclude = Availability.where(:event_id => params[:id]).select(:user_id).pluck(:user_id)
if #exclude.count > 0
#players = User.where('team_id = ? and id NOT IN (?)', current_user[:team_id], #exclude).all
else
#players = User.where('team_id =?', current_user[:team_id])
You could do something like this:
#availabilities = Availability.where(event_id: params[:id]).pluck(:id)
#players = User.where(team_id: current_user[:team_id])
#players = #players.where('id NOT IN (?)', #availabilities) unless #availabilities.empty?
Using pluck() will return an array of IDs, then you can exclude them by using NOT IN (?)
Try:
id not in
The way pg engine sees it is ((team_id=1 and id <> 101), 102, 103). Thus the error you see.
Use it as:
User.where('team_id = ? and id not in (?)', current_user[:team_id], #availabilities).all

Resources