accepts_nested_attributes_for with find_or_create?

When you define a hook for autosave associations, the normal code path is skipped and your method is called instead. Thus, you can do this: class Post < ActiveRecord::Base belongs_to :author, :autosave => true accepts_nested_attributes_for :author # If you need to validate the associated record, you can add a method like this: # validate_associated_record_for_author def … Read more

Eager load polymorphic

My guess is that your models look like this: class User < ActiveRecord::Base has_many :reviews end class Review < ActiveRecord::Base belongs_to :user belongs_to :reviewable, polymorphic: true end class Shop < ActiveRecord::Base has_many :reviews, as: :reviewable end You are unable to do that query for several reasons. ActiveRecord is unable to build the join without additional … 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

How to use ANY instead of IN in a WHERE clause?

There are two variants of IN expressions: expression IN (subquery) expression IN (value [, …]) Similarly, two variants with the ANY construct: expression operator ANY (subquery) expression operator ANY (array expression) A subquery works for either technique, but for the second form of each, IN expects a list of values (as defined in standard SQL) … Read more

tech