开发者

How to Skip Validations w/ find_or_create_by_?

开发者 https://www.devze.com 2023-03-30 14:33 出处:网络
Is it possible to skip validations with a d开发者_StackOverflowynamic find/create by method? For example with regular save I can do something like:

Is it possible to skip validations with a d开发者_StackOverflowynamic 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.


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.


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.


Currently skipping validation DOES work with find_or_create_by.

For example, running:

  Contact.find_or_create_by(email: "hello@corsego.com).save(validate: false)

will skip a validation like:

  validates :name, :email, presence: true, uniqueness: true
0

精彩评论

暂无评论...
验证码 换一张
取 消