How to convert ActiveRecord results into an array of hashes

as_json You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name tasks_records = TaskStoreStatus.all tasks_records = tasks_records.as_json # You can now add new records and return the result as json by calling `to_json` tasks_records << TaskStoreStatus.last.as_json tasks_records << { :task_id => 10, :store_name => “Koramanagala”, :store_region => “India” } tasks_records.to_json … Read more

How can I see the SQL that will be generated by a given ActiveRecord query in Ruby on Rails

Similar to penger’s, but works anytime in the console even after classes have been loaded and the logger has been cached: For Rails 2: ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT) For Rails 3.0.x: ActiveRecord::Base.logger = Logger.new(STDOUT) For Rails >= 3.1.0 this is already done by default in consoles. In case it’s too noisy and you want to turn … Read more

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

Where it is documented: From the API documentation under the has_many association in “Module ActiveRecord::Associations::ClassMethods” collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if … Read more

When to use a “has_many :through” relation in Rails?

Say you have these models: Car Engine Piston A car has_one :engine An engine belongs_to :car An engine has_many :pistons Piston belongs_to :engine A car has_many :pistons, through: :engine Piston has_one :car, through: :engine Essentially you are delegating a model relationship to another model, so instead of having to call car.engine.pistons, you can just do … Read more

Is there a way to get a collection of all the Models in your Rails app?

The whole answer for Rails 3, 4 and 5 is: If cache_classes is off (by default it’s off in development, but on in production): Rails.application.eager_load! Then: ActiveRecord::Base.descendants This makes sure all models in your application, regardless of where they are, are loaded, and any gems you are using which provide models are also loaded. This … Read more

Specifying column name in a “references” migration

For Rails 5+ Initial Definition: If you are defining your Post model table, you can set references, index and foreign_key in one line: t.references :author, index: true, foreign_key: { to_table: :users } Update Existing: If you are adding references to an existing table, you can do this: add_reference :posts, :author, foreign_key: { to_table: :users } … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)