如何跳过rails中特定功能的模型验证?

时间:2013-02-19 07:20:21

标签: ruby-on-rails ruby ruby-on-rails-3

我想跳过控制器功能的一些模型验证。我这样做

型号:

attr_accessible :skip_method_2
validates :name,  presence: true, length: { maximum: 50 }, :unless => :skip_method_2
VALID_PHONE_REGEX = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
validates :phoneno, presence: true,uniqueness: { case_sensitive: false, :scope => :user_id}, format: { with: VALID_PHONE_REGEX }, :unless => :skip_method_2

控制器:

def contacts_callback
 @contacts = request.env['omnicontacts.contacts']   
 @contacts.each do |contact|
   next if current_user.contacts.exists?(:email => "#{contact[:email]}")
   contact1 = current_user.contacts.new(:skip_method_2 => true)
   contact1.name = contact[:name] 
   contact1.email = contact[:email]
   contact1.group = "Others"
   contact1.save
 end
  redirect_to "/contact"
end

我不想保存它:validation =>假。我想跳过contacts_callback函数的名称和phoneno验证。但它没有用。

它在控制器中出错 - 未定义的局部变量或contacts_callback的方法`skip_method_2'。我已经在我的模型中提到了attr_accessible

1 个答案:

答案 0 :(得分:1)

更改validates :name, presence: true, length: { maximum: 50 }, :unless => :skip_method_2

validates :name, presence: true, length: { maximum: 50 }, :unless => lambda {|x| x.skip_method_2}

同时结帐this回答