Rails select values - ruby-on-rails

I have a select option in a form:
<%= f.select :role, options_for_select(User.roles.keys.to_a, params[:role]), {}, class: 'form-control form-control-lg roleSelect' %>
These roles are defined in my model:
enum role: {user: 0, profile_user: 1}
Now in my dropdown when the user choses it shows user and profile_user as drop down option.
Is there any way to show another value to represent these in a drop down?
For example:
In the drop down I would rather show "I am a teacher" which maps to user.
In the drop down I would rather show "I am here to study" which maps to profile_user.

In your model add your narrative descriptions.
NARRATIVE_ROLES = {user: 'I am a teacher', profile_user: 'I am here to learn'}
Add a method to create the select_array
def self.roles_select
User.roles.keys.map {|role| [NARRATIVE_ROLES[role], role]}
end
Then in the select you use
options_for_select(User.roles_select, params[:role])
Or (slightly simpler)
NARRATIVE_ROLES = {'I am a teacher' => :user, 'I am here to learn' => :profile_user}
options_for_select(User::NARRATIVE_ROLES, params[:role])

Related

Rails 4 - how to write a helper method to present attribute names

I have a roles table with an attribute :name in it.
I'm trying to use a list of role names in a collection select. Instead of listing the :name in the way it is recorded in the database, I want to present it neatly.
For example, :name has an instance stored as :admin in the database. I want to present that in the collection select as 'Administrator'.
I tried to write a roles helper that says:
module RolesHelper
def text_for_role(name)
case name
when 'guest'
'Guest - Trial Account'
when 'admin'
'Administrator'
when 'representative'
'Representative'
etc, etc
but this option isn't going to work in this context, because I want to list all the roles, but refer to them written nicely.
I have this collection select:
<%= select_tag "roles", options_from_collection_for_select(#roles, "id", "<%= text_for_role(name)%>"), :multiple => true, :class => 'chosen-select form-control' %>
Can anyone see how I can write a helper or a presenter that can be used on the whole list of collection select options?
create a class level variable like:
class MyClass
ROLES = [
['Guest - Trial Account' ,'guest' ],
['Administrator' , 'admin'],
['Representative' , 'representative']
]
end
Then access them on the view:
<%= select_tag 'roles', MyClass::ROLES %>
More Info : Here

Select_tag: Style and Modify Options Upon Condition

I have a form_categories table which has a column called active which is of type tinyint/boolean. If the form category record's active attribute is true, then it is active. If false, then it is inactive.
I have a select box that displays all of the records within the form_categories table. I want to style the inactive form_category options red in order to convey to the user that that form_category is inactive. Or Even better, I'd like to put in parentheses next to each inactive form_category option: (inactive) in red letters.
Is this possible?
Below is my select box:
<%= form_tag some_path, method: :get do %>
<%= label_tag "Choose Category" %><br>
<%= select_tag :category_id, options_from_collection_for_select(FormCategory.all, :id, :name), include_blank: true %>
<% end %>
You can use options_for_select and provide the options hash yourself:
options_for_select(form_categories_options, 1) # Where 1 is the current selected option; you would use some value passed from the controller for it
For form_categories_options, you can use a helper, like:
def form_categories_options
FormCategory.all.map do |form_category|
if form_category.inactive
["#{form_category.name} (inactive)", form_category.id]
else
[form_category.name, form_category.id]
end
end
end
If you really want to use options_from_collection_for_select, you can tweak the third argument, namely the text_method: you can define a formatted_name method in your FormCategory model:
class FormCategory < ActiveRecord::Base
...
def formatted_name
if inactive
"#{name} (inactive)"
else
name
end
end
...
end
then use it:
options_from_collection_for_select(FormCategory.all, :id, :formatted_name)

options_from_collection_for_select in rails 4

I'm building a simple form to let users of my rails 4 site message each other.
In the form, the user can select the recipient of the message with a select list of all the users in the system (it's a small user base).
Right now the form control looks like this, and works fine:
<%= f.select(:to_id, options_from_collection_for_select(User.all, :id, :first_name), {}, {:class => 'form-control'}) %>
However, there's a "nickname" field in the Users table as well-- I'd like to have the form show the nickname (if it exists) as well as the user's first / last name-- so the value of the select would be:
<option>Snoop Dogg - Calvin Broadus</option>
rather than just
<option>Calvin</option>
Is this possible?
Make a display_name on the Users model
def display_name
nickname || first_name
end
Then update your form to reference it
<%= f.select(:to_id, options_from_collection_for_select(User.all, :id, :display_name), {}, {:class => 'form-control'}) %>

Rails how to use f.select with virtual attributes

I have a user model that contains 2 booleans in the database - admin, and readonly. Basically this allows me to have 3 levels of access (readonly, editable, and admin).
I have a screen that allows admins to edit other users permissions. Instead of having 2 checkboxes for the boolean values of admin and readonly, i created a dropdown using f.select and i created a virtual attribute called "permission".
Everything works fine when saving a user as far as permissions go, the only thing is that when you go to the edit page for a particiular user, it does not load the page with the user's actual permission in the dropdown. It just loads the first value in the dropdown as the default value.
How can i make it so this dropdown shows the users actual permission when first loading the user edit page?
Here's my virtual attribute code for my User model:
# get the permission
def permission
if self.read_only
#permission = 'readonly'
elsif self.admin
#permission = 'admin'
else
#permission = 'editable'
end
end
# Set the permission.
def permission=(value)
p "VALUE = #{value}"
if value == 'readonly'
self.read_only = true
self.admin = false
#permission = 'readonly'
elsif value == 'admin'
p "INSIDE admin"
self.read_only = false
p "before #{self.admin}"
self.admin = true
p "after #{self.admin}"
#permission = 'admin'
elsif value == 'editable'
self.read_only = false
self.admin = false
#permission = 'editable'
end
end
and here's my f.select in my form view:
<%= f.select :permission, options_for_select([['Admin', 'admin'], ['Read Only', 'readonly'], ['Editable', 'editable']], {:disabled => #permissions_disabled}) %>
I tried using collection_select, but couldn't figure out how to populate the list.
as stated in Rails f.select trying to disable a dropdown from being changed, you dont need the options_for_select. If you remove it and pass the fourth parameter a selected option, you should be set.
<%= f.select :permission, [['admin', 'Admin'], ['readonly', 'Read Only'], ['editable', 'Editable']], { selected: 'readonly' }, { disabled: #permissions_disabled } %>
but given the code above, even without the selected option, as long as f.object.permission returns the right value, you should be fine.
Try adding this to your last options hash: :selected => #user.permission
For example:
<%= f.select :permission, options_for_select([['Admin', 'admin'], ['Read Only', 'readonly'], ['Editable', 'editable']], {:disabled => #permissions_disabled, :selected => #user.permission}) %>

need to add default value in f.select field to existing ones - rails 3.2

With the code I have below in the select field I have all the public_campaigns:
<%= f.select :campaign_id, #public_campaigns.map{|x| [x.name,x.id]} %>
public_campaigns is defined in controller with:
#public_campaigns = #logged_in_user.campaigns.order('created_at desc')
In the form I select the campaign and fill up the rest of the form and at the submit action an invitation is created with campaign_id taken from the campaign I selected in the form, it can be anything from 1 to n
What I need now is to have a default item in select field that will have the value of 0 and named "No campaign", it means I invite someone to a campaign that I have not created yet and in invitation the campaign_id field will be 0.
Thank you for your time.
Do you really need 0? I think use of {:include_blank => "No campaign"} should be enough?
Try this:
<%= f.select :campaign_id, (#public_campaigns.map{|x| [x.name,x.id]} << ["No campaign",0]), {:selected => 0} %>
Well, the fastest way you can do this is something like this:
#public_campaigns = #logged_in_user.campaigns.order('created_at desc')
no_campaign = Campaign.new(:id => '0', :name => 'No Campaign')
#public_campaigns.unshift(no_campaign)
I'm not sure why you are unable to do it this way:
<%= f.collection_select :campaign_id, #public_campaigns, :id, :name, prompt: 'No campaign' %>
Just check if campaign_id.nil? instead of assigning any value to campaign_id

Resources