In a controller I have a code which isn't associated with the model directly:
def create
var1 = get_some_post_param
# check if var1 isn't nil -- how to add an error the model if it is?
# some other code...
@m = Model.new(field1: var1, field2: var2, field3: var3)
if @m.save
# ok
#....
else
# error
...
end
end
How can I add a validation error to the model right after var1 = get_some_post_param
if var1
is nil?
First of all, I don't think you can directly do that in your controller.
You can associate the non-model var1
attribute to any one of your model attribute (this can be a new attribute for this purpose, say: special_var1
).
Then in your controller you can have:
before_action :set_special_var1
def set_special_var1
var1 = get_some_post_param
@m.special_var1 = var1
end
And, then in your model, you can add a custom validator:
# model.rb
validate :special_var1_is_not_nil
private
def special_var1_is_not_nil
if self.special_var1.nil?
errors.add(:special_var1, 'special_var1 is nil')
end
end
Or, you can also try:
validates :special_var1, allow_nil: false
However, these validations will be invoked before the object is being persisted eg when you call: @m.save
, not before that.
The best you can do in your controller is, having a before_action
in your controller and then redirect to some page if var1
is nil
:
before_action :check_var1
private
def check_var1
var1 = get_some_post_param
unless var1
redirect_to "index", notice: "Invalid var1"
end
end
See this post for some reference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.