Reputation: 2951
I have one model but two different forms ,one form i am saving through create
action and another one through student_create
action.I want to validate a field in student_create action form and leave other one free.How do i do it?Any help will be appreciated
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
I have tried this but it didnt work
class Book < ActiveRecord::Base
validates_presence_of :town ,:if=>:student?
def student?
:action=="student_create"
end
end
Also this didnt work
class Book < ActiveRecord::Base
validates_presence_of :town ,:on=>:student_create
end
Upvotes: 1
Views: 428
Reputation: 2230
Sounds like you have two types of books. not sure what your domain logic is but the normal flow I would do nothing.
class Book < ActiveRecord::Base
end
Then for the path you want an extra validation you could do this:
class SpecialBook < Book
validates :town, :presence => true
end
If this is the case you might want to consider Single Table Inheritance.
In another case you might want to save the student_id on the book.
Then
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
Upvotes: 0
Reputation: 2951
I was able to acomplish it what i wanted to do by giving it an option :allow_nil=>true
Upvotes: 0
Reputation: 8954
In the one that should not be validated you do this:
@object = Model.new(params[:xyz])
respond_to do |format|
if @object.save(:validate => false)
#do stuff here
else
#do stuff here
end
end
the save(:validate => false)
will skipp the validation.
Upvotes: 2