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

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

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)

Heroku Postgres Error: PGError: ERROR: relation “organizations” does not exist (ActiveRecord::StatementInvalid)

I had the same problem. To solve it, resetting the database is more easier. heroku rake db:reset (‘heroku run rake db:reset’ if you’re on cedar) heroku rake db:migrate (‘heroku run rake db:migrate’ if you’re on cedar) Then, migration was done successfully for my case 🙂 While this is a good solution in this context, don’t … Read more

Counting the number of queries performed

I think you answered your own question by mentioning assert_queries, but here goes: I would recommend taking a look at the code behind assert_queries and using that to build your own method which you can use to count queries. The main magic involved here is this line: ActiveSupport::Notifications.subscribe(‘sql.active_record’, SQLCounter.new) I had a bit of a … Read more

Rails: Validate only on create, or on update when field is not blank

If you want to allow blank values use: allow_blank with validates. class Topic < ActiveRecord::Base validates :title, length: { is: 5 }, allow_blank: true end If you want to validate only on create, use on with validates. class Topic < ActiveRecord::Base validates :email, uniqueness: true, on: :create end To cover your case: class Topic validates … Read more