Declaring Instance Variable In View and Passing To Model
I am trying to conditionalize validation of fields being sent in a view by passing a variable from the view to the model so it knows which set of fields to check.
The model looks like this:
validates_presence_of :first_name, :last_name, :if => :registration_step?
validates_numericality_of :primary_phone, :if => :contact_step?
def registration_step?
@step == :register
end
def contact_step?
开发者_如何学JAVA@step == :contact
end
I'm not sure what I have to place in my view in order for everything to function properly. I've tried
<% @step = :register %>
and
<% @step = :contact %>
As well as some other combinations (:step, and also @step with 'register' and 'contact'. I know it's just a matter of syntax or I'm just missing one more thing in the model but I can't figure it out.`
Instance variables set in a view won't make it to the model, not directly at least. The problem you are describing–the conditional part–is something we were just trying to deal with today.
I think your best bet is to have an attr_accessor
on your model which you can set in your controller's create, update, whatever action–this is something that shouldn't be set in the view. Once in your model, you could have a method which checks the value of this attribute in your if
conditions for validation. Definitely don't pass this as a hidden field from your form, though. You do not want to trust this sort of thing to be potentially manipulated by a user.
Reply to comment:
If you add step
as an attr_accessor
, in your controller, you should be able to do something like
@my_model = MyModel.new(params[:model])
@my_model.step = :register
if @my_model.save...
And, in your model, something along the lines of
validates_presence_of :first_name, :last_name, :if => :registration_step?
def registration_step?
step == :register
end
精彩评论