Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form field not part of rails db model

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?

like image 841
cman77 Avatar asked Jun 16 '12 02:06

cman77


People also ask

What are forms in Rails?

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.


1 Answers

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
like image 73
Nobita Avatar answered Sep 20 '22 15:09

Nobita