How to implement Active Record inheritance in Ruby on Rails?

Rails supports Single Table Inheritance. From the AR docs: Active Record allows inheritance by storing the name of the class in a column that by default is named “type” (can be changed by overwriting Base.inheritance_column). This means that an inheritance looking like this: class Company < ActiveRecord::Base; end class Firm < Company; end class Client … Read more

How to use long id in Rails applications?

Credits to http://moeffju.net/blog/using-bigint-columns-in-rails-migrations class CreateDemo < ActiveRecord::Migration def self.up create_table :demo, :id => false do |t| t.integer :id, :limit => 8 end end end See the option :id => false which disables the automatic creation of the id field The t.integer :id, :limit => 8 line will produce a 64 bit integer field

Why isn’t self always needed in ruby / rails / activerecord?

This is because attributes/associations are actually methods(getters/setters) and not local variables. When you state “parent = value” Ruby assumes you want to assign the value to the local variable parent. Somewhere up the stack there’s a setter method “def parent=” and to call that you must use “self.parent = ” to tell ruby that you … Read more

Rails Object Relationships and JSON Rendering

By default you’ll only get the JSON that represents modelb in your example above. But, you can tell Rails to include the other related objects as well: def export @export_data = ModelA.find(params[:id]) respond_to do |format| format.html format.json { render :json => @export_data.to_json(:include => :modelb) } end end You can even tell it to exclude certain … Read more

Rails create or update magic?

Rails 6 Rails 6 added an upsert and upsert_all methods that deliver this functionality. Model.upsert(column_name: value) [upsert] It does not instantiate any models nor does it trigger Active Record callbacks or validations. Rails 5, 4, and 3 Not if you are looking for an “upsert” (where the database executes an update or an insert statement … Read more

Converting an array of objects to ActiveRecord::Relation

You can convert an array of objects arr to an ActiveRecord::Relation like this (assuming you know which class the objects are, which you probably do) MyModel.where(id: arr.map(&:id)) You have to use where though, it’s a useful tool which you shouldn’t be reluctant to use. And now you have a one-liner converting an array to a … Read more

Find all records which have a count of an association greater than zero

1) To get Projects with at least 1 vacancy: Project.joins(:vacancies).group(‘projects.id’) 2) To get Projects with more than 1 vacancy: Project.joins(:vacancies).group(‘projects.id’).having(‘count(project_id) > 1’) 3) Or, if Vacancy model sets counter cache: belongs_to :project, counter_cache: true then this will work, too: Project.where(‘vacancies_count > ?’, 1) Inflection rule for vacancy may need to be specified manually?