ActiveRecord includes. Specify included columns

Rails doesn’t have the facility to pass the options for include query. But we can pass these params with the association declaration under the model. For your scenario, you need to create a new association with users model under the profile model, like below belongs_to :user_only_fetch_email, :select => “users.id, users.email”, :class_name => “User” I just … Read more

How to validate the date such that it is after today in Rails?

Your question is (almost) exactly answered in the Rails guides. Here’s the example code they give. This class validates that the date is in the past, while your question is how to validate that the date is in the future, but adapting it should be pretty easy: class Invoice < ActiveRecord::Base validate :expiration_date_cannot_be_in_the_past def expiration_date_cannot_be_in_the_past … Read more

Rails 4 scope to find parents with no children

Update Rails 6.1 With the new Rails version this becomes simple, as described here: .where.missing(:children) For older versions see below. Rails 3 & 4 scope :without_children, includes(:children).where(:children => { :id => nil }) The big difference here is the joins becoming a includes: an include loads all the relations, if they exists, the join will … Read more

In Rails’ ActiveRecord, what is touch for?

As per the API Documentation, it is a method that only updates the specified timestamps of the model with the current time. So in order to update the updated_at field: product.touch or to update the updated_at and designed_at fields: product.touch(:designed_at) Now, I have never used this method before, but I’d think it would be useful … Read more

Getting “Unknown primary key for table” while the ID is there

Seems primary key is missing for the table collections. Prior to Rails 3.2, set the primary key in model like class Collection < ActiveRecord::Base set_primary_key “my_existing_column” end In Rails 3.2+ and Rails 4, set the primary key in model like class Collection < ActiveRecord::Base self.primary_key = “my_existing_column” end OR We can alter the table and … Read more

Rails includes with scope

I think the best solution would be: Author.includes(:articles).where(:articles=>{published: true}).find(params[:author_id]) Or you can create scope: class Author < ActiveRecord::Base scope :with_published_articles, -> { includes(:articles).where(articles: { published: true}) } end and then: Author.with_published_articles.find(params[:author_id].to_s)