I have a form with checkbox that enables/disables another field:
<%= check_box_tag :enable %>
<%= text_input_tag :extra_parameter %>
The model will store the extra parameter if enable is true. With _tag I will need to pass the extra parameters from the controller to the model.
Is there a way to do this using form builder and have the logic completely in the model?
View:
<%= f.check_box :enable %&g开发者_运维知识库t;
<%= f.text_input :extra_parameter %>
Model:
class ExampleModel < ActiveRecord::Base
def enable=
????
end
def extra_parameter=
self.extra_parameter = true if ???
end
end
One way is instance variable - but this presumes the model 'enable' will be called before 'extra_parameter'. Is this the best way? is there alternative?
You would need to do this by overriding the initialize
method in order to be able to do something like this in your controller and have it just work:
ExampleModel.new(:extra_params => "Hello world", :enabled => true)
Your model would look something like the below, which overrides initialize, calling super
first to set any accessible attributes, and then setting extra_params
using our custom setter. We need to do this in this order because, like you mentioned, we need to ensure that enabled
is set and returns the correct boolean value when we decide whether or not to set extra_params
.
class ExampleModel < ActiveRecord::Base
def initialize(attrs={})
super(attrs)
self.extra_params = attrs.fetch(:extra_params, nil)
end
def extra_params=(value)
self[:extra_params] = value if enabled?
end
end
With this method, the order that you set the parameters in when new-ing up the object shouldn't matter.
For attributes that don't have an equivalent column in the databas, you can use attr_accessor:
attr_accessor :enable
def extra_parameter=(value)
self[:extra_parameter] = value if enable
end
As long as "enable" is passed before "extra_parameter" in a mass assignment, this will work. I'm not sure if that order can be enforced, though.
精彩评论