Jomar Gregorio
Jomar Gregorio

Reputation: 171

Custom Validation in Model with Parameter from controller

i have this chunk of codes in my controller

def create
  number = params[:number]
  @color = Colors.new(params[:colors])
  @color.save       
end

and i have this validation in model color.rb

validate :should_be_primary

def should_be_primary
   #validations here
end

I just want the validation should only run when my params[:number] == 1

Note: params[:number] is only a parameter and not a table field.

anyone please help me.

Upvotes: 2

Views: 785

Answers (2)

endyey Es
endyey Es

Reputation: 509

def create
  number = params[:number]
  params[:colors][:param_number] = number
  @color = Colors.new(params[:colors])
  @color.save       
end

validate :should_be_primary
def param_number=(number)
 @number = number
end

def should_be_primary
   if @number
     #blah blah
   end
end

Upvotes: 4

Lymuel
Lymuel

Reputation: 574

Try this on your model.rb

validate :should_be_pimary if self.number == 1

def should_be_primary
   #validations here
end

Upvotes: 3

Related Questions