一个模型中的条件验证,但有两种不同的形式

时间:2011-11-13 23:20:06

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

我有一个模型但有两种不同的表单,一种是我通过create操作保存的表单,另一种是student_create操作。我想验证student_create操作表单中的字段并保留其他一个免费我怎么做?任何帮助将不胜感激

 class BookController < ApplicationController
     def create
      if @book.save
     redirect_to @book    #eliminated some of the code for simplicity
      end 
     end

     def student_create
     if @book.save            #eliminated some of the code for simplicity
      redirect_to @book
     end
     end

我试过这个,但它没有用

      class Book < ActiveRecord::Base
        validates_presence_of :town ,:if=>:student?

    def student?
    :action=="student_create"
    end
    end

这也没有用

      class Book < ActiveRecord::Base
        validates_presence_of :town ,:on=>:student_create
       end

3 个答案:

答案 0 :(得分:2)

在不应该验证的那个中你执行此操作:

@object = Model.new(params[:xyz])

respond_to do |format|
     if @object.save(:validate => false)
          #do stuff here
     else
          #do stuff here
     end
end

save(:validate => false)将跳过验证。

答案 1 :(得分:0)

我能够通过给它一个选项:allow_nil=>true

来完成我想做的事情

答案 2 :(得分:0)

听起来你有两种类型的书。不确定你的域逻辑是什么,但正常流程我什么都不做。

class Book < ActiveRecord::Base

end

然后,对于您想要额外验证的路径,您可以执行此操作:

class SpecialBook < Book
  validates :town, :presence => true
end

如果是这种情况,您可能需要考虑单表继承。


在另一种情况下,您可能希望将student_id保存在书上。

然后

class Book < ActiveRecord::Base
  validate :validate_town

  private
    def validate_town
      if student_id
        self.errors.add(:town, "This book is evil, it needs a town.") if town.blank?
      end
    end
end
相关问题