Hey guys I'm a rails newbie and I have a question about select boxes in forms. Here is my code right now.
<%= form_for #message do |f| %>
<%= f.text_field :name %>
<%= f.select :topic ['Test1', 'test2']
<% end %>
Now, this code works for submitting the information in the text boxes, but for some reason not the information in the select box. However my main question is, Is there a way that I can make a select box and rails automatically include: "Please select an option" and that way when I do validates_presence_of :topic on the select box it will return false if it hasn't been changed?
Also, do any of you think you know why the select box isn't submitting info to my database?
Thanks in advance!
Yes, what you want is easy to do. Just add a pair of values, your placeholder text and a blank value, to the beginning of your select options. Try this:
<%= f.select :topic, [['Please select an option', nil], 'Test1', 'test2'] %>
Related
i'm new with ruby on rails and i've an issue.
In my app, an user can publish an idea and ideas belongs to activities.
So user can choose with a select which activity they want.
Here's my code for my form, i used collection_select
<div class="field">
<%= collection_select(:idee, :id, Activite.all, :id, :nom, prompt: true) %></div>
The select input work, i've all my activities in the select input but when i select activity and publish my idea, the idea don't take the value and stay empty.
Even when i edit idea, the idea don't take the value of the activity.
How can i resolve this ?
Given that you have an Idea and an Activity model and that you are building a form for an idea, I think you should write the collection_select as:
<%= collection_select(:idea, :activity_id, Activity.all, :id, :nom, prompt: true) %>
I suggest you to use form_for syntax if you are not already doing it.
check apidock for reference:
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select
http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for
I am trying to allow a user to input two different things in two different drop down menus from the same form and it will store an integer into a review table.
I want the user to be able to select model_name in one drop down and manufacturer in another drop down. The result will store a bat_id integer into the form. (Telling you which bat the user is selecting)
I have seen a couple questions about date & time but they store the values directly in the model. I am trying to store an integer - bat_id so that the bat_id will directly link the review model to the bat model.
Examples I have found that are close:
How do ruby on rails multi parameter attributes really work (datetime_select)
Rails multiple fields to one model attribute
Using multiple input fields for one attribute
Rails Update Single Attribute with Multiple Fields
My form now:
<%= form_for(#review) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field" align= "center">
<h3>Select Brand</h3>
<%= f.collection_select :manufacturer_id, Manufacturer.all, :id, :manufacturer, include_blank: true %>
<h3>Select Bat</h3>
<%= f.grouped_collection_select :bat_id, Manufacturer.all, :bats, :manufacturer, :id, :model_year_and_name, include_blank: true %>
<h3>What do you like about this bat?</h3>
<%= f.text_area :pros, placeholder: "Enter what you like..." %>
<h3>What do you not like about this bat?</h3>
<%= f.text_area :cons, placeholder: "Enter what you don't like..." %></br>
</div>
<div align="center">
<%= f.submit "Add Review", class: "btn btn-large btn-info" %>
</div>
<% end %>
I am submitting to the review table and trying to submit both of these to the bat_id attribute.
<h3>Select Brand</h3>
<%= f.collection_select :manufacturer_id, Manufacturer.all, :id, :manufacturer, include_blank: true %>
<h3>Select Bat</h3>
<%= f.grouped_collection_select :bat_id, Manufacturer.all, :bats, :manufacturer, :id, :model_year_and_name, include_blank: true %>
In my bat model I have: has_many :reviews & In my reviews model I have: belongs_to :bat
UPDATE: Is it possible to use a hidden field with the combination of javascript and my two inputs to determine my one output bat_id?
Update I changed my dropdown code to what works so that I enter in manufacturer_id & bat_id when both are selected. However I still think there is a way to store one value in my review model. I am using javascript very similiar to this
From a UI perspective this seems broken... users will be able to associate any model year & name with any manufacturer, even if that manufacturer did not produce that model year & name.
Assuming you will introduce some javascript to handle that, from a rails perspective you will get undefined behavior with two :bat_id fields in the same form. I think you need this:
<h3>Select Brand</h3>
<%= f.collection_select :manufacturer_id, Manufacturer.all, :id, :manufacturer, include_blank: true %>
<h3>Select Bat</h3>
<%= f.collection_select :bat_id, Bat.all, :id, :model_year_and_name, include_blank: true %>
Alternatively you can just create one dropdown containing a composite field, like this:
<h3>Select Bat</h3>
<%= f.collection_select :bat_id, Bat.all.sort {|a, b| a.manufacturer_model_year_and_name <=> b.manufacturer_model_year_and_name}, :id, :manufacturer_model_year_and_name, include_blank: true %>
and then in your Bat model introduce something like this:
def manufacturer_model_year_and_name
"#{self.manufacturer.name}: #{self.model_year_and_name}"
end
As discussed in your other answer, you shouldn't need to store the manufacturer_id on your review model.
I would recommend creating a Manufacturer select that isn't accessed in your Review model, but is simply used to filter the list of bats on the form.
The best way to do this is probably to add some custom data attributes to the Bat select.
<%= collection_select :manufacturer, :manufacturer_id, Manufacturer.all, :id, :manufacturer %>
<%= f.select :bat_id, Bat.all.map{ |b| [b.model_year_and_name, b.id, {'data-manufacturer' => b.manufacturer_id}] } %>
Then use some javascript to filter the Bat select when the Manufacturer select is changed.
Unfortunately you cannot just set display: none to an option element to hide it. This does not hide the option in many browsers. So the best method is to use a bit of jQuery to clone the original select every time the manufacturer select is changed, and remove any option that isn't associated with the selected manufacturer. Like so:
// rename the original select and hide it
$('#bat_id').attr('id', 'bat_id_original').hide();
$('#manufacturer_id').on('change', function() {
$('#bat_id').remove(); // remove any bat_id selects
$bat = $('#bat_id_original')
.clone() // clone the original
.attr('id', 'bat_id') // change the ID to the proper id
.insertAfter('#bat_id_original') // place it
.show() // show it
.find(':not(option[data-manufacturer="' + $(this).val() + '"])')
.remove(); // find all options by other manufacturers and remove them
});
You might need to change a few things to get this to work in your installation, but you can view a static demo on jsFiddle here: http://jsfiddle.net/JL6M5/
You will probably need to reject the manufacturer_id field on form submit, avitevet already pointed out this answer which should help there: Rails: Ignoring non-existant attributes passed to create()
I have this code in my form :
guidances/new.html.erb
<%= f.association :employee_department, as: :select %>
<%= f.input :guidance_supervisor do %>
<%= f.select :guidance_supervisor,
Employee.where('guidance_supervisor' => true).map(&:full_name) %>
<% end %>
and when selecting a department I need to make the employees who belongs to that department appears, I'm using simple_form , what is the way to make this happen ?
For this you can use dynamic drop-down concept. You can see the following post for dynamic drop down in rails:
Dynamic drop down in rails.
I have a problem on my application.
I have collection select code
<% baskets.each do |f| %>
<%= f.select :link, #books.collect{|x| [x.title, x.id]}.unshift(['Please select','']) %>
<% end %>
How do I make the select option editable like a text field so that I can copy and paste the link to choose from the book collections?
I've never tried this. Do you have any suggestion?
Thanks for your help :)
Instead of using a select field you could use a text field with auto complete.
What is the easiest and most graceful way to auto-submit an AJAX form when a drop-down box's option is selected? I'm creating an administration page where the admin can modify user permissions (where "permissions" is stored as an integer), and I would like the "permissions" field to be a drop-down box that automatically submits and updates when the administrator clicks on the option he wants the user to have.
Here's the stripped-down version of what I'm currently looking at. I need to know the best way to convert this to a remote form that automatically submits when an option is clicked on.
Feel free to point out any tangential suggestions or anything else...I'm relatively new to Rails, and only just reaching the point where I can write code without constantly referencing others' work.
<!-- This is the "index" view, by the way. -->
<% for membership in #story.memberships %>
<% form_for membership do |f| %>
<%= f.select :permissions, [['none', 0], ['admin', 9]] %>
<% end %>
<% end %>
There are a couple ways to handle this. Certainly the observe field approach is one, but you could also use a simple javascript or a remote_function to do it:
Here is the simple JS approach:
<% remote_form_for membership do |f| %>
<%= f.select :permissions, [['none', 0], ['admin', 9]], {}, :onchange => 'this.form.submit()' %>
<% end %>
The other way would be something like this, and would eschew the form builder (and this may have a couple syntax errors):
<%= select_tag(:permissions, [['none', 0], ['admin', 9]], {:onchange => "#{remote_function(:url => permissions_path(:story_id => story,
:with => "'permission='+value")}"})
Personally I prefer the former.
Three steps!
Make your form_for a remote_form_for; add an id!
Add an observe_field after your select
Configure your observe_field to submit your form
The last bit looks something like:
<%= observe_field "id_of_select", :function => "$('form_id').submit();" %>
In Rails 3:
<%= form_for(membership, :remote => true) do |f| %>`
<%= f.select :permissions, [['none', 0], ['admin', 9]], {}, :onchange => 'this.form.submit();' %>
<% end %>
Note that it's this.form.submit(); not onsubmit. And don't forget the Javascript semicolon.
Learn how to do it without Rails using the framework of your choice. Using the Rails tags to perform AJAX can accomplish a task quickly, but can be very limiting when you need to change specific things about how the tag performs.
Read about web-standards and how to write unobtrusive javascript on these sites:
http://ajaxian.com/
http://www.alistapart.com/
You'll be able to create more flexible, amazing UIs by learning how to perform AJAX without Rails.
I am using Rails 5 & I was also facing the similar situation but in my case the answer given by #scott was not submitting the form using AJAX as expected though I added the remote: true option to the form (I don't have submit button in the form).
If somebody is also facing the similar problem try to change the JS code like this-
<% form_for membership remote: true, id: '#member_form' do |f| %>
<%= f.select :permissions, [['none', 0], ['admin', 9]], onchange: '$("#member_form").trigger("submit");' %>
<% end %>
Hope this helps..