Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

skip validation after create mongoid rails

I want to skip a validation after an object is created. Lets take an example

person has many company and company has many people

person has many placements and placement belongs to person person can have only one active placement

Placement model has one validation that checks if a person already has an active placement when saved.

@placement is active placement
@employment.placement = @person

if @placement.save
  #################
  @person.placements << @placement
  @company.placements << @placement
end

Now when the placement is saved for the first time, No problem its gets saved.

Now the problem comes when

@person.placements << @placement

Since the person already has active placement through @placement.save.

@person.placements << @placement again saves @placement and the validation fires validation error to @placement object.

Is there any way so that i tell not to go through that specific validation some where in ############ region of my code.

Or any alternative solutions are welcome.

Thanks

like image 454
Gagan Avatar asked Jan 26 '11 05:01

Gagan


2 Answers

you can use: save :validate => false

like image 131
Alex Avatar answered Oct 20 '22 14:10

Alex


The first thing if you want to save after all the validations passes then do something like this

if @placement.valid?
  @person.placements << @placement
  @company.placements << @placement
end

Next thing is if you are using mongoid then << operator call .save on both documents.

The solution may be either overwrite << of mongoid, Or need to speacify validation during which action.

validates :placeholder, :on => :create And Or

if @placement.valid?
  @placement.person = @person
  @company.placements << @placement
end
like image 1
kriysna Avatar answered Oct 20 '22 13:10

kriysna