Mario Zigliotto Mario Zigliotto - 6 months ago 25
Ruby Question

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
.

Answer

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.