Ruby on Rails: Skipping 'validate_on_create' statement for seeds

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

I have a 'validate_on_create' statement in one of my controllers that I would like all of my seed data to skip. What are some solutions so that the create statement in my seeds file skips this validation. My current solution is commenting out the validation each time I run rake db:seed. Anything a little more clever?

回答1:

Have you considered adding an attribute in the model which is checked in the validate_on_create method?

Example:

class MyModel < ActiveRecord::Base    attr_accessor :skip_on_create_validation    def validate_on_create     unless skip_on_create_validation       # do validation     end   end  end  # In db/seeds.rb MyModel.create(:skip_on_create_validation => true, ......)


回答2:

You can skip validations by calling model.save(false) on your seeds, assuming you are not loading them via fixtures.



回答3:

You can explicitly skip all validations when you save an object by calling object.save(false).

For example:

# In your model def validate_on_create   # An example validation - replace with whatever you like   return true unless name.blank? end  # In db/seeds.rb # Create a new person p = Person.new(:name => 'Bob') # Save the record to the database, and *skip validation* p.save(false)


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!