Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Skip Validations w/ find_or_create_by_?

Is it possible to skip validations with a dynamic find/create by method?

For example with regular save I can do something like:

p = Post.new
p.title = nil
p.body = nil
p.save(:validate => false)

Would love to do the same with find_or_create_by_title.

like image 919
Mario Zigliotto Avatar asked Aug 23 '11 04:08

Mario Zigliotto


3 Answers

It dosnt look possible with the code in Rails right now however you may have better luck being a little more verbose in how you write the code. You can use find_or_initialize_by_ which creates a new object but does not save it. You can then call save with your custom options, also in the documentation they have a neat demonstration that is hard to find so I will include it below:

# No 'Winter' tag exists
winter = Tag.find_or_initialize_by_name("Winter")
winter.new_record? # true

Good luck and let me know if you need more pointers in the right direction.

like image 166
Devin M Avatar answered Nov 15 '22 00:11

Devin M


For some cases, find_or_initialize_by_ will not be useful and need to skip validations with find_or_create_by.

For this, you can use below alternative flow and method of ROR:

Update your model like this:

class Post < ActiveRecord::Base
  attr_accessor :skip_validation
  belongs_to :user
  validates_presence_of :title, unless: :skip_validation
end

You can use it now like this:
Post.where(user_id: self.id).first_or_create!(skip_validation: true)

I have used first_or_create instead of find_or_create_by here. You can pass more column names and values with this, and your validation will not be worked with this.

  • You can continue without any changes for strong parameters end and no need to permit this 'skip_validation' so it will work with validations while adding entries.

  • Using this, you can use it with and without validations by passing a parameter.

like image 20
RohitPorwal Avatar answered Nov 15 '22 02:11

RohitPorwal


Currently skipping validation DOES work with find_or_create_by.

For example, running:

  Contact.find_or_create_by(email: "[email protected]).save(validate: false)

will skip a validation like:

  validates :name, :email, presence: true, uniqueness: true
like image 2
Yshmarov Avatar answered Nov 15 '22 00:11

Yshmarov