简体   繁体   English

验证Ruby on Rails模型

[英]validation for models in ruby on rails

I have a model: 我有一个模型:

class HelloRails < ActiveRecord::Base
  attr_accessible :filename, :filevalidate
  include In4systemsModelCommon

  validates :filename, presence: true

  def update
      parameters = [self.filename, @current_user]
      parameters.map!{|p| ActiveRecord::Base.connection.quote p}
      sql = "call stored_procedure(#{parameters.join(',')})"
      ActiveRecord::Base.connection.execute(sql)
  end
end

In the view I have a text_field called as :filename . 在视图中,我有一个text_field称为:filename When I click the submit button it calls this update method in model to call the stored proc to execute. 当我单击提交按钮时,它将在模型中调用此更新方法以调用存储的proc来执行。 Now validations are not working. 现在验证不起作用。

I dont want to accept nil for filename. 我不想接受nil作为文件名。 How can I do this? 我怎样才能做到这一点?

It doesn't validate because you are executing sql directly: 由于您直接执行sql,因此无法验证:

ActiveRecord::Base.connection.execute(sql)

Validations are only run when you use the "normal" ActiveRecord methods like save and update_attributes . 仅当使用诸如saveupdate_attributes类的“正常” ActiveRecord方法时,才运行验证。 To run validations manually you can call valid? 要手动运行验证,可以致电valid? on your object. 在你的对象上。

Model: 模型:

def update
  return false unless self.valid? # validation failed: return false
  parameters = [self.filename, @current_user]
  parameters.map!{|p| ActiveRecord::Base.connection.quote p}
  sql = "call stored_procedure(#{parameters.join(',')})"
  ActiveRecord::Base.connection.execute(sql)
  true
end

Then in your controller you have to check wether @object.update returns true or false and display errors in your view if necessary. 然后,在控制器中,您必须检查@object.update是否返回truefalse并在必要时在视图中显示错误。

Controller: 控制器:

# This is just an example. I don't know your code.
def update
  @object = HelloRails.find(params[:id])

  if @object.update
    redirect_to somewhere
  else
    render :action => 'edit'
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM