Reputation: 266978
Is it possible to make a attribute required just for a particular form?
The field is nullable in the model, and there is no validation setup for it currently and I want to keep it that way.
But on 1 form, I would like to make the field required.
Is this possible without creating a separate model for this?
Upvotes: 0
Views: 633
Reputation: 4115
I know that you doesn't want to touch the model, but you can do a conditional validation like this that isn't invasive
validates_presence_of :your_attribute, :if => :from_specific_form?
and create some methods that work with this
private
def from_form
@from_specific_form = true
end
def from_specific_form?
@from_specific_form
end
Then when you want the validation to work, just do something like this
xyz = YourModel.new
xyz.from_form
Upvotes: 0
Reputation: 1705
You could use ActionController
s require
for the used parameters, something like this:
def person_params
params.require(:person).permit(:name).tap do |person_params|
person_params.require(:name) # SAFER
end
end
http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-require
Does that help you?
Upvotes: 1