Rails where condition using NOT NIL

Rails 4+ ActiveRecord 4.0 and above adds where.not so you can do this: Foo.includes(:bar).where.not(‘bars.id’ => nil) Foo.includes(:bar).where.not(bars: { id: nil }) When working with scopes between tables, I prefer to leverage merge so that I can use existing scopes more easily. Foo.includes(:bar).merge(Bar.where.not(id: nil)) Also, since includes does not always choose a join strategy, you should … Read more

Rails: Access to current_user from within a model in Ruby on Rails

I’d say your instincts to keep current_user out of the model are correct. Like Daniel I’m all for skinny controllers and fat models, but there is also a clear division of responsibilities. The purpose of the controller is to manage the incoming request and session. The model should be able to answer the question “Can … Read more

ActiveRecord OR query Hash notation

There are 5 options that could be considered as implementations of «Hash notation» (the last two are kinda hash-ish): With Ruby on Rails 5 you are able to do the following chaining using ActiveRecord::Relation#or method: Person.where(name: ‘Neil’).or(Person.where(age: 27)) Use where_values together with reduce. The unscoped method is necessary only for Rails 4.1+ to ensure default_scope … Read more

Rails 4: List of available datatypes

Here are all the Rails 4 (ActiveRecord migration) datatypes: :binary :boolean :date :datetime :decimal :float :integer :bigint :primary_key :references :string :text :time :timestamp Source: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column These are the same as with Rails 3. If you use PostgreSQL, you can also take advantage of these: :hstore :json :jsonb :array :cidr_address :ip_address :mac_address They are stored as … Read more

How can I avoid running ActiveRecord callbacks?

Use update_column (Rails >= v3.1) or update_columns (Rails >= 4.0) to skip callbacks and validations. Also with these methods, updated_at is not updated. #Rails >= v3.1 only @person.update_column(:some_attribute, ‘value’) #Rails >= v4.0 only @person.update_columns(attributes) http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_column #2: Skipping callbacks that also works while creating an object class Person < ActiveRecord::Base attr_accessor :skip_some_callbacks before_validation :do_something after_validation :do_something_else … Read more