In Rails 3 how should I manage a model column with limited choices - ruby-on-rails

In my Rails 3 application I have numerous models that have columns that have limited choices (IE a select box). It seems overkill in these cases to create another model and a relationship to the original model just to manage the choices.
One option I can think of is to just create a select box and have the choices in there, but that doesn't seem very DRY. Does anyone have a good suggestion how to handle this situation?
Thanks for looking.

You could create a constant in your model like so
# formatted as an array of options, option being an array of key, value
OPTIONS = [['Email', 'email'], ['Text', 'text'], ['Email and Text', 'both']]
validates_inclusion_of :field, :in => OPTIONS
Which can then be used to populate a select menu in a view very easily
Example using formtastic
<%= f.input :field, :as => :select, :collection => Model::OPTIONS %>

I usually do this with a constant list in the model.
class Model < ActiveRecord::Base
PROPERTY_OPTIONS = ['Option One', 'Option Two', ...]
validates_inclusion_of :property, :in => PROPERTY_OPTIONS
end
And in the view:
<%= f.select :property, Model::PROPERTY_OPTIONS %>

You can also use the enum_column plugin: https://github.com/electronick/enum_column
You can then render your select boxes in your views as follows:
<%= f.select :status, Model.columns_hash['status'].limit %>
(Where Model is an example model name, such as Book or Product, or whatever it is your application is really about.)

In some cases, I will just create a hash of options and use Class Methods to display and set them. For example, a Problem model with different statuses could be done like so:
def self.statuses
{:open => 1, :closed => 2}
end
Then you just store the integer value in the status_id of the model. You can configure getters/setters as well.

Related

ActiveAdmin: display parameter of object selected in form

I am not very familiar with ActiveAdmin or rails in general, so sorry if I use some incorrect phrasing.
I have a model for an Athlete, which has an attribute "notes". This is described in the permit_params of the athlete.rb.
On an additional page, I have the following:
f.input :athlete, :collection => Athlete.all.sort_by(&:last_name), :required => true
I would like to find a way to, if the :notes is not empty, display it.
If I could display it as a "row" on the form, that would be great.
Thanks!

Rails:how to show name instead of ID or Address in has_many relation in active_admin?

These days I'm using the active_admin to manage my data. I have a Audio model and Problem model. Audio has many problems and Problem belongs to audio.
I use the active_admin to create the problems. But in the problem's new page, there is a drop-down list shows the content like:
#<Audio:0xb4116084>
With the address I can hardly recognize which file I want. What I want to show in the Audio's drop-down list is the Audio's title which is a column of Audio model. I just want to change this column in the new page, and others remain the same as default. What should I do? Thanks!
Audio class must implement display_name method
Ex
class Audio
def display_name
title
end
end
this is from active admin sources
# Active Admin makes educated guesses when displaying objects, this is
# the list of methods it tries calling in order
setting :display_name_methods, [ :display_name,
:full_name,
:name,
:username,
:login,
:title,
:email,
:to_s ]
Looks like you haven't such methods so to_s is called for Audio objects
You can use a :member_label.
Here is a example
form :html => { :enctype => "multipart/form-data" } do |f|
f.input :problems,
:input_html => { :multiple => false, :style => "width: 700px;"},
:collection => Audio.all,
:member_label => :audio_name
end

ruby on rails how to use FormOptionHelpers to create dynamic drop down list

I have checked some tutorials but I got confused by the parameters in this method
collection_select (object, attribute, collection, value_method, text_method, options = {}, html_options ={})
I have a map model includes: :area, :system, :file
and I want to read :area from database to a drop down list, and let user choose one
I already did #map = Map.all in the view
what the method should be?
especially the parameter "attribute". In a lot tutorials, people put "id" here. But I don't know what "id" is, and in my situation I don't need any other value, just the "area".
Im not exactly sure what you are asking here but if you are trying to make a dropdown selection for use in an html form will this example help you at all?
<% nations = {'United States of America' => 'USA', 'Canada' => 'Canada', 'Mexico' => 'Mexico', 'United Kingdom'=> 'UK'} %>
<% list = nations.sort %>
<%= f.select :country, list, %>
Here nations is a hash of countries then list becomes the sorted copy of that hash. An html dropdown is then created as a part of the form "f". ":country" is the part of the model that the data is connected to while list is the options to populate the dropdown with
It's not clear from your question what the model is that's being populated with the area.
Typically, collection_select is used between related models.
eg.
class Category < ActiveRecord::Base
has_many :products
end
class Product < ActiveRecord::Base
belongs_to :category
end
When selecting the 'category' for a product, your view would have something like:
<%= f.collection_select(:category_id, :id, Category.all, :name, include_blank: true) %>
What this does is specify the Product.category_id as the attribute being populated with the value of Category.id. The values come from the Category.all collection, and with Category.name being the item displayed in the select. The last (optional) parameter says to include a blank entry.
Something like the following is probably what you need:
<%= f.collection_select(:map_id, :id, #map, :area) %>
However, if the model you're trying to populate has an area attribute (instead of an ID linking to the map), you might need to use:
<%= f.collection_select(:area, :area, #map, :area) %>
This specifies that the area attribute of the receiving table will be populated with Map's area attribute, which is also being used as the "description" in the select.

How do I generate a bunch of checkboxes from a collection?

I have two models User and Category that have a HABTM association.
I would like to generate checkboxes from a collection of Category items on my view, and have them associated with the current_user.
How do I do that?
Thanks.
P.S. I know that I can do the equivalent for a dropdown menu with options_from_collection_for_select. I also know that Rails has a checkbox_tag helper. But not quite sure how to do both of them. I know I can just do it manually with an each loop or something, but am wondering if there is something native to Rails 3 that I am missing.
Did you check out formtastic or simple_form
They have helpers to write your forms more easily, also to handle simple associations.
E.g. in simple_form you can just write
= simple_form_for #user do
= f.association :categories, :as => :check_boxes
In form_tastic you would write
= simple_form_for #user do
= f.input :categories, :as => :check_boxes
Hope this helps.
You can use a collection_select and feed it the options. Assuming you have a form builder wrapped around a user instance, you can do something like this:
form_for current_user do |f|
f.collection_select(
:category_ids, # the param key, so params[:user][:category_ids]
f.object.categories, # the collection of items in the list
:id, # option value
:name # option string
)
end
You may want to pass the :multiple => true option on the end if needed.

Rails form not saving 'Type:' field

I generated a simple Post scaffold which has title:string body:text category:string. I later added type:string (and performed the migration) to the model and added the selection fields in new.html.erb and edit.html.erb. I also added validation for all these fields.
<%= f.label :type %>
<%= f.select :type, Post::TYPES, :prompt => "Select post type" %>
When I try and create a post it gives me:
"There were problems with the following fields:
Type can't be blank
Type is not included in the list"
Even though I DO make a selection. Am I missing something obvious here?
Select code from Post class:
TYPES = [
["Job", "job"],
["Volunteer", "vol"]
]
validates_presence_of :title, :body, :category, :type
validates_inclusion_of :category, :in => CATEGORIES.map {|disp, value| value}
validates_inclusion_of :type, :in => TYPES.map {|disp, value| value}
The type field is a reserved field used for single table inheritance(STI). You have to rename the field.
Refer to this article for more details
Edit: Changed the link to point to the article provide by Matchu.
If you really want to, you can use field called type in Rails 4 by setting inheritance_column to something else:
class Product < ActiveRecord::Base
self.inheritance_column = :ruby_type
end
In Rails 3 and below, use method set_inheritance_column instead.

Resources