I have a field on a form i'm trying to access in the corresponding model, but it is not part of the models database table. What is the best way to handle this? Is this bad practice?
Rails provides a series of helpers for generating form elements such as checkboxes, text fields, and radio buttons. These basic helpers, with names ending in _tag (such as text_field_tag and check_box_tag ), generate just a single <input> element. The first parameter to these is always the name of the input.
It is ok to have model attributes that are not in the database table. These are called virtual attributes.
Let's say you want to deal with an attribute called 'virtual_attribute'. Here is how you would deal with it:
While in your form you would have something like this:
<%= f.check_box :virtual_attribute %>
In your model you would have to do this:
attr_accessor :virtual_attribute
Notice that this is a built-in Ruby method that gives you the setter and the getter for that attribute:
#getter
def virtual_attribute
@virtual_attribute
end
#setter
def virtual_attribute=(value)
@virtual_attribute = value
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With