Lets say I have an instructions table which is associated to a surveys table through survey_instructions join table. What I need to achieve is to fetch all instruction records, but ordered by an …
Tag: ruby-on-rails
SQL query to Rails query (Case Statement)
This is my SQL query: SELECT user_id, CASE responsible WHEN 1 THEN “true” ELSE “false” END AS responsible FROM user_departments How do I write this in rails? I tried a query as below: …
Rails Postgres query, selecting only items that appear in all search params with associations
I’m looking to create a Postgres query based on a few user select params. A user will select a shop and a start and end year. Once submitted I’m would only like to display average prices of items if …
Avoid N+1 query in large data set
I have a migration which updates existing records with a new attribute value. The model is called ‘MyRecord’. It has millions of records in the database with a new unit_id column of null. I want to …
Rails/PostgreSQL – Query to update all dates adding 1 day
I want to execute an update_all query to update a datetime column adding 1 day to the current value of this column on all rows. I could achieve that using .each and .update, but it would be more …
rails – shouldn’t I use default values in rails migration
I am not sure whether I should ask this question on SO or not. But I have to as I don’t have clear idea about my doubt. I was told not to set default values in rails migrations and use null values instead in a code review by our CTO. And his explanation is like this once the database gets
Rails query comparing one col from table Payment and sum of table Transaction
There are Payment (id, total) and Transaction (payment_id, amount) table in our database (simplified for post). Payment’s id is in Transaction and they can be joined together if needed. Here is what …
Raills: Get SQL generated by delete_all
I’m not particularly familiar with Ruby on Rails, but I’m troubleshooting an issue we’re experiencing with a rake job that is supposed to be cleaning database tables. The tables grow very large very …
Rails Query with ILIKE
I have written a finder as follows: params[:manufacturer] comes through in a form of a string that has been .parameterized by Rails. The problem is that a string with an “‘” or an “&” in it doesn’t get matched by ILIKE correctly. So as an example, some strings that are stored in my DB and their parameterized versions: “This is
Rails Activerecord Relation: using subquery as a table for a SQL select statement
Can somebody help me figure out how to write the following SQL using Rails (I’m using Rails 4) Activerecord methods? I know you can do this with find_by_sql but I’d like to preserve the active record relation. Here’s the sql for a postGreSQL db that I’m trying to create: For my subquery, I have the following (which generates the sql