Reputation: 5009
Apologies in advance for the total beginner question, but since I am a beginner here goes: In my Rails 3 app I have an attribute on my Profile
model for :subject
. In my form, I have the following code for the user to assign the :subject
:
<%= f.select :profile_subject, options_for_select([['Select', 0], ['Arts', 1], ['Biology', 2], ['Business', 3], ['Chemistry', 4], ['English', 5], ['Foreign Language', 6], ['Government', 7], ['Health', 8], ['History', 9], ['Math', 10], ['Physics', 11], ['Vocational', 12]]) %>
I want to utilize the :subject
strings for two things really:
I don't think I set this up in my database (or built the form) properly, as I only appear to be storing the id ("ex: 1") and not the string ("ex: Arts"). Before I remove the option id though, I'm curious: For something like this, is it considered good practice to include an option id as well as a string in the select? Or strip the id and just keep it as an array of strings only?
The reason for asking all this is regarding my search form. As I mentioned I'm using Ransack, and I'm just not sure how to make the f.select
work with just a bunch of strings.
Upvotes: 3
Views: 5381
Reputation: 9858
I would store the array of subjects in the model for several reasons. You can use it for validation.
class Profile < ActiveRecord::Base
SUBJECT_VALUES = %w( Arts Biology Business Chemistry English Foreign\ Language Government Health History Math Physics Vocational )
validates_inclusion_of :subject, :in => SUBJECT_VALUES
end
Your new/edit form can use that easily.
<%= f.select :subject, Profile::SUBJECT_VALUES %>
And your search form.
<%= f.select :profile_subject_eq, Profile::SUBJECT_VALUES %>
And if you want to allow multiple select for searching.
<%= f.collection_select :profile_subject_in, Profile::SUBJECT_VALUES, :to_s, :to_s, {}, { :multiple => true } %>
Upvotes: 1
Reputation: 5009
First, I hadn't set this up properly in my db. So I corrected the form so the :subject stored was a string. Here's the new form:
<%= f.select :subject, options_for_select([['Select', ''], ['Arts'], ['Biology'], ['Business'], ['Chemistry'], ['English'], ['Foreign Language'], ['Government'], ['Health'], ['History'], ['Math'], ['Physics'], ['Vocational']], :selected => @profile.subject) %>
Then for the search form I just had to add a predicate _eq
:
<%= f.select :profile_subject_eq, options_for_select([['Select', ''], ['Arts'], ['Biology'], ['Business'], ['Chemistry'], ['English'], ['Foreign Language'], ['Government'], ['Health'], ['History'], ['Math'], ['Physics'], ['Vocational']], :selected => :profile_subject) %>
And now it works.
Upvotes: 7