How to save a model without running callbacks in Rails

I believe what you are asking for can be achieved with ActiveSupport::Callbacks. Have a look at set_callback and skip_callback. In order to “force callbacks to get called even if you made no changes to the record”, you need to register the callback to some event e.g. save, validate etc.. set_callback :save, :before, :my_before_save_callback To skip … Read more

after_create with multiple methods?

No need to surround the methods in array. Simply use: after_create :do_this, :and_then_this Bonus Information: If a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the … Read more

Rails first_or_create ActiveRecord method

From the Guides first_or_create The first_or_create method checks whether first returns nil or not. If it does return nil, then create is called. This is very powerful when coupled with the where method. Let’s see an example. Suppose you want to find a client named ‘Andy’, and if there’s none, create one and additionally set … Read more

How do I add migration with multiple references to the same model in one table? Ruby/Rails

You can do this simply with the add_column method in your migrations and set up the proper associations in your classes: class AddFields < ActiveRecord::Migration def change add_column :tickets, :image_1_id, :integer add_column :tickets, :image_2_id, :integer end end class Ticket < ActiveRecord::Base belongs_to :image_1, :class_name => “Image” belongs_to :image_2, :class_name => “Image” end class Image < … Read more

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

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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)