0

我正在使用一个包含总共 7 个模型的嵌套表单,每个模型都有不同的验证。简单地编辑表单时,验证运行并显示正常,并且数据被正确保存。但是,我需要根据提交表单的人员运行不同的验证(即,管理员可以跳过一些原本需要的字段)。

我想我可以通过在我的模型中使用 attr_accessible :editing_user 来跳过某些验证,然后在控制器中设置它。

class ModelExample < ActiveRecord::Base
  attr_accessible :editing_user
  validates_presence_of :email, :unless => "editing_user == 'admin'"
end

class ModelExamplesController < ActionController::Base
  def create
    @model_example = ModelExample.new(params[:model_example])
    @model_example.editing_user = 'admin'
    @model_example.save
  end
end

我在嵌套模型中使用了这个基本结构,检查是否可以正确保存。这就是奇怪行为开始的地方。出于某种原因,ActiveRecord 似乎试图多次保存嵌套模型,每次都运行验证。奇怪的是我调用了@model_example.save,如果失败,它应该只返回false。但是,第一次验证通过(因为设置了 editing_user),但后来的验证失败并引发异常,因此正常的 .save 方法最终引发异常而不是返回。

有谁知道如何避免让 ActiveRecord 进行所有额外的验证和保存,或者如何在这些重复的操作中保留 editor_user?

4

1 回答 1

1

哈!刚刚做了这个酵母,好吧,几乎相同的用例(坚持用户)。以下是我解决它的方法(感谢我复制的好友 Jason Dew):

class User < ActiveRecord::Base

  module ClassMethods
    attr_accessor :current
  end

  extend ClassMethods
end

此代码块向 User 类方法添加了一个单例访问器 :current,并且可以称为 User.current。看起来更好看的方法称为self.currrent

然后在应用程序控制器中

before_filter :require_user #=> which in this case goes off and sets the current_user var
before_filter {|c| User.current = current_user}

它将应用程序控制器传递给块并设置 User.current var。

然后在任何其他模型中

class MyClass < ActiveRecord::Base
  def log
    "This was done by #{User.current}"
  end
end
于 2010-08-05T16:55:17.410 回答