2011-11-13 46 views
1

我有一个模型,但两种不同的形式,我通过create行动和另一个通过student_create行动保存一种形式。我想验证student_create行动形式中的字段,并留下其他形式free.How做呢?任何帮助将不胜感激有条件验证在一个模型中,但两种不同的形式

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 

回答

0

我能够acomplish它是什么我想给它一个选项:allow_nil=>true

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)意志skipp验证。

+0

问题是有需要在'create'虽然验证等领域 – katie

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 
相关问题