I have model,
class Test < ActiveRecord::Base
as_enum :test, [:test, :test_1, :test_1_2]
end
I need to create a f.select dropdown with enum. But I am facing an issue preparing dropdown with enum.
Here is my code:
<%= f.select :test, options_for_select(Test.tests.keys.to_a), {}, :class => "form-control" %>
But prepared a wrong select box.
http://grab.by/HSM2
Can anyone have any suggestion?
Use the code below. Titleize function capitalizes all the words and replaces the underscores with spaces. You can read more about it here
<%= f.select :test, Test.tests.keys.map {|test| [test.to_s.titleize, test]}, {}, :class => "form-control" %>
Related
I have a Sezzion model:
attr_accessible :description
has_many :session_instructors, :dependent => :destroy
has_many :instructors, :through => :session_instructors
accepts_nested_attributes_for :session_instructors
accepts_nested_attributes_for :instructors
Instructor model:
attr_accessible :bio
has_many :sezzions, :through => :session_instructors
has_many :session_instructors, :dependent => :destroy
SessionInstructor model:
attr_accessible :instructor_id, :sezzion_id
belongs_to :sezzion
belongs_to :instructor
Lastly, User model:
has_many :sezzions
has_many :instructors
I'm trying to create a form for Sezzion with nested form for SessionInstructor which has multiple select option for Instructors.
How can I do the following:
nested form for SessionInstructor
use multiple select option to get all the selected Instructor's instructor_id
hidden field to pass in the created/updated session_id with each select instructor
I have the following code as of now:
<%= form_for(#sezzion) do |f| %>
<%= f.label :description %>
<%= f.text_area :description %>
<%= f.label :instructors %>
<%= fields_for :session_instructors do |f| %>
<select multiple>
<% current_user.instructors.each do |instructor| %>
<option><%= instructor.name %></option>
<% end %>
</select>
<% end %>
<%= f.submit %>
<% end %>
Thank you so much!
This is something that seems ridiculously hard in Rails.
I think something like this might work:
<%= f.fields_for :session_instructors do |si| %>
<%= si.collection_select :instructor_ids, current_user.instructors, :id, :name, multiple: true>
<% end %>
This should create a form element which will set sezzion[session_instructors_attributes][instructor_ids].
Although I'm not sure if that's actually what you want. I've never tried this using a multi select. If it doesn't work, you could also try getting rid of the fields_for and just using f.collection_select. If you're willing to use a checkbox, I can show you how to do that for sure.
I hope that helps.
Edit:
Here's how I would usually do it with a check_box:
<%= f.fields_for :session_instructors do |si| %>
<%= si.hidden_field "instructor_ids[]" %>
<% current_user.instructors.each do |i| %>
<%= si.check_box "instructor_ids[]", i.id, i.sezzions.include?(#sezzion), id: "instructor_ids_#{i.id}" %>
<%= label_tag "instructor_ids_#{i.id}", i.name %>
<% end %>
<% end%>
There are a couple "gotchas!" with this method. When editing a model, if you deselect all checkboxes then it won't send the parameter at all. That's why the hidden_field is necessary. Also, you need to make sure each form element has a unique id field. Otherwise only the last entry is sent. That's why I manually set the value myself.
I copy pasted and then edited. Hopefully I got the syntax close enough where you can get it to work.
FINAL EDIT:
Per Sayanee's comment below, the answer was a bit simpler than I thought:
<%= f.collection_select :instructor_ids, current_user.instructors, :id, :name, {}, {:multiple => true} %>
#Sayanee, can you post how your instructors, sezzions table look like. Also for note, you can not get instructor_ids from Instructor object, hence you are getting "undefined method" error. With the current association that you shared, you can get instructor_ids from a Sezzion object. So you need to loop through current_user.sezzions in stead of current_user.instructors.
This is a way to implement fields_for nested form with html multiple_select in case of a has_many :through association. Solved it by doing something like this. The form view:
<%= form_for(#sezzion) do |f| %>
...
<%= fields_for :session_instructors do |g| %>
<%= g.label :instructor, "Instructees List (Ctrl+Click to select multiple)" %>:
<%= g.select(:instructor_id, Instructor.all.collect { |m| [m.name, m.id] }, {}, { :multiple => true, :size => 5 }) %>
<%= g.hidden_field :your_chosen_variable_id, value: your_chosen.id %>
<% end %>
...
<%= f.submit %>
<% end %>
Note:Since the #sezzion would not be saved at the time of generating the form you cannot pass that id (#sezzion.id) in place of your_chosen.id through the form. You could handle that save in the controller.
Make sure that your controller Initializes the Variables while generating the form: Your def new could look something like this:
def new
#sezzion = Sezzion.new
#sezzion.session_instructor.build
#sezzion.instructors.build
end
Now the create controller has to be able to accept the strong params required for the multiple select, so the sezzion_params method may look something like this:
def sezzion_params
params.require(:sezzion).permit(:description, :any_other_fields,
:session_instructors_attributes =>
[:instructor_id => [], :your_chosen_id => Integer])
end
In the create function, the first session_instructor variable is linked to the #sezzion instance variable through our new function. The other session_instructors in our multiple select must be built after the Sezzion instance is saved, if you want to pass in the created #sezzion.id with each select instructor. .
def create
#sezzion = Sezzion.new(sezzion_params)
#startcount=1 #The first element of the array passed back from the form with multiple select is blank
#sezzion.session_instructors.each do |m|
m.instructor_id = sezzion_params["session_instructors_attributes"]["0"]["instructor_id"][#startcount]
m.your_chosen_variable_id = your_chosen.id
#startcount +=1
end
if #sezzion.save
sezzion_params["session_instructors_attributes"]["0"]["instructor_id"].drop(#startcount).each do |m|
#sezzion.session_instructors.build(:instructor_id => sezzion_params["session_instructors_attributes"]["0"]["instructor_id"][#startcount],
:your_chosen_variable_id => your_chosen.id).save
#startcount += 1
end
flash[:success] = "Sezzion created!"
redirect_to root_url
else
flash[:danger] = "There were errors in your submission"
redirect_to new_sezzion_path
end
end
I'm definitely a bit of a noob, so this might be something simple that I'm overlooking, however, the searches that I've done to try and find a solution have come up empty.
I've built a form using formtastic that has 5 input fields: two are text boxes and three are select lists.
<%= semantic_form_for #player do |f| %>
<%= f.inputs do %>
<%= f.input :firstname, :label => "First Name " %>
<%= f.input :lastname, :label => "Last Name " %>
<%= f.input :leagueid, :as => :select, :collection => League.all(:order => :leaguename), :label => "League " %>
<%= f.input :team_1, :as => :select, :collection => Team.all(:order => :name), :label => "Team 1 " %>
<%= f.input :team_2, :as => :select, :collection => Team.all(:order => :name), :label => "Team 1 " %>
<% end %>
<%= f.actions %>
<% end %>
What is happening is that the Teams lists work perfectly (the team names are displayed). However, the League list is a different story. All of the entries in the list look like this (with different a different code after 'League:'):
#<League:0x007fe29c406498>
If I use the form to create a Player, it works fine. The correct league ID goes into the database and everything. I just can't figure out why the names of the teams show, while whatever-that-is shows for the league.
Any and all help is appreciated.
When converting objects to String, Ruby will convert them to the memory address like you see unless you provide a to_s method for string conversions. I haven't used formtastic, but I believe adding a to_s method to your League class should cause it to display what you want.
Try adding
def to_s
#name # use whatever you want to be displayed.
end
to the League class.
You could try explicitly specifying the fields that should be used as the text and id within the select list. I believe it would look like.
<%= f.input :leagueid, :as => :select, :collection => Hash[League.all.map { |league| [league.leaguename, league.id] }]
The syntax is crazy. The call to map is returning an array of name/id pairs, like [ ['league1', 1], ['league2', 2] ]. Calling Hash on that converts it to a hash, like {'league1' => 1, 'league2' => 2}. Seems like the select list should use this hash to populate itself.
There's an example of this at http://rdoc.info/github/justinfrench/formtastic, under the Usage section.
:member_name is the solution I think.
<%= f.input :leagueid, :as => :select, :collection => League.all(:order => :leaguename), :label => "League " %>
Will probably work for you as
<%= f.input :leagueid, :as => :select, :member_name => :league, :collection => League.all(:order => :leaguename), :label => "League " %>
My problem was I have a model with a field the same name as the model and I think that confused Formtastic
Example scaffold:
rails g scaffold Countries code:string country:string
rails g scaffold Types title:string description:string
Model:
class Sign < ActiveRecord::Base
attr_accessible :title, :country_id, :type_id
belongs_to :country
belongs_to :type
Form View:
<%= f.input :type %>
<%= f.input :country, :member_label => :country %>
Having a form without the member_label leads to the object id displaying in the select box for countries although the ID is correctly saved. The type select worked perfectly without declaring member_label.
Note that I didn't need to specify :as => :select as formtastic can deduce this from the belongs_to relationship.
Try using :
<%= form.input :league, :member_label => :leaguename %>
This will override the naming convention of the Formtastic Column Select.
Have a look also at : Overriding the Column Name Convention wiki
Hope this helped.
I'm looking for a Rails plugin providing a builder for show.html.erb pages.
For example, with SimpleForm, an new.html.erb page might look like this :
<%= simple_form_for(#user, :url => user_registration_path, :html => ... }) do |f| %>
<%= f.input :email, :required => true %>
<%= f.input :password, :required => true %>
<%= f.input :password_confirmation, :required => true %>
...
<% end %>
But I was not able to find an equivalent for just displaying fields.
A generated show.html.erb page looks like :
<p>
<b>Email:</b>
<%= #user.email %>
</p>
...
But I'd like something like :
<%= simple_display_for(#user, :html => ... }) do |d| %>
<%= d.output :email %>
<%= d.output :name %>
...
<% end %>
Does this kind of builder exist?
Thanks
EDIT : If the builder use Twitter Bootstrap, that's even better :)
I don't know of any gems, but here is a simple example of how to build this feature yourself, which you can expand on:
lib/simple_output.rb
class SimpleOutput
def initialize(resource)
#resource = resource
end
def output(attribute)
#resource.send attribute
end
end
config/initializers/simple_output.rb
require_dependency 'lib/simple_output'
helpers/simple_output_helper.rb
module SimpleOutputHelper
def simple_output_for(resource, options={}, &block)
content_tag :div, yield(SimpleOutput.new(resource)), options[:html] || {}
end
end
users/show.html.erb
<%= simple_output_for(#user, html: { style: "background-color: #dedede" }) do |r| %>
<%= r.output :name %>
<%= r.output :email %>
<% end %>
Now, obviously this is just a very simple example, but hopefully it will get you started on the right track. Look at the simple_form source to see how they organize their code, and how they "typecast" fields. The simple_form codebase is very clean and easy-to-follow Ruby, and is a great example of what a gem should look like.
How can I specify the label class when using f.association instead of f.input in simple_form?
For example, this works:
f.input :name, :label_html => { :class => 'some-class' }
But this doesn't
f.association :periods, :as => :check_boxes, :label_html => { :class => 'some-class' }
Meaning that the label related to :name will have some-class as part of its class, but the label related to :periods won't. Any way to do this without changing f.association to f.input? Thank!
I think you can't add custom class to each label but you can do it for each item wrapper, e.g:
<%= simple_form_for(#user) do |f| %>
<%= f.association :group, as: :check_boxes, item_wrapper_class: 'custom-class' %>
<%= f.button :submit %>
<% end %>
If I would like to assign a class to my embedded ruby form, like so?:
<%= form_for(User.new) do |f|, :class => "form-horizontal" %>
How could I go about doing it? I keep getting a syntax error.
Thanks!
from http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for
form_for(record, options = {}, &proc)
meaning:
<%= form_for(User.new, { :class => 'form-horizontal' }) do |f| %>