This question already has answers here:
Can someone explain collection_select to me in clear, simple terms?
(2 answers)
Closed 8 years ago.
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})public
for e.g.
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)
In this helper - Please explain, What is object and method in detail? Is :post a model name and :author_id a fieldname in a model or are they tag name.
can they be anything I want, not necessarily :post and author_id, instead :post123 or auth_id. Will it be perfectly ok?
Please explain be in detail. thanks in advance
I can give a brief explanation
:post - The object you are manipulating. In this case, it's a Post object.
:author_id - The field that is populated when the Post is saved.
And they are supposed to be like that.you can't replace those with any strings or symbols.
I think you also need this
Author.all - The array you are working with.
:id - The value that is stored in the database. In terms of HTML, this is the tag's value parameter
:name_with_initial- The output that the user sees in the pull-down menu. This is the value between the <option> tags.
Hope it Helps!
collection_select(
:post, # field namespace
:author_id, # field name
# result of this two params will be: <select name="post[author_id]">...
# then you should specify some collection or array of rows.
# It can be Author.where(..).order(..) or someting like that.
# In you example it is:
Author.all,
# then you should specify methods for generating options
:id, # this is name of method that will be called for every row, result will be set as key
:name_with_initial, # this is name of method that will be called for every row, result will be set as value
# as a result, every option will be generated by the following rule:
# <option value=#{author.id}>#{author.name_with_initial}</option>
# 'author' is row of collection or array
:prompt => true # then you can specify some params. You can find them in doc.
)
answered here Can someone explain collection_select to me in clear, simple terms? by alexkv (This link should help you to get explanation.)
Related
This is my code - it's working fine but I want to be able to select multiple Organisations, while this select only allows me to choose one.
<%= f.collection_select :id,
Organisation.order(:Company_Name),
:id,
:Company_Name,
options = {include_blank: "Select an Organisation"},
html_options = {:onchange => 'broadcast_dropdown_change(document.getElementById("broadcast_country_id"), document.getElementById("broadcast_organisation_id"))'} %>
Please help me resolve this, along with any advice on how I can improve this code.
Thank you.
I think you just need to add the html option multiple: true :) Hopefully that'll do it, nice and easily!
If not, you'll need to ensure the permitted parameters match up to what's getting passed through - likely a JSON encoded array of options - and parse / save them as appropriate in the database.
Couple more examples available in the duplicate I've linked in the comment to your post. Let me know how you get on and I'll provide a little more info if need be!
Update based on your comment, here's an example:
<%= f.collection_select :id,
Organisation.order(:Company_Name),
:id,
:Company_Name,
{ include_blank: "Select an Organisation" },
onchange: 'broadcast_dropdown_change(document.getElementById("broadcast_country_id"), document.getElementById("broadcast_organisation_id")',
multiple: true %>
Couple of notes here:
the last two arguments this method takes are for options and html_options; the include_blank: ... is in the former, and the final two arguments the latter
you don't need to assign these hashes to variables. The first hash needs the brackets to distinguish it from the second, though the final hash is implicit so doesn't require the brackets (though you can use them, if you find it easier to read, i.e.)
{ onchange: 'broadcast_dropdown_change(document.getElementById("broadcast_country_id"), document.getElementById("broadcast_organisation_id")',
multiple: true }
have a quick look at how you're naming your variables - it's worth spending the time to format them correctly - for example, :Company_Name should always be lower snake case :company_name
Hope that helps - again, give me a shout and let me know how you get on :)
I am trying to make a multi select dropdown work with a dialog for search parameters. I can make the dropdown multi select but can't seem to get/pass the resulting data. (edited/new info will be in italics)
I believe that the root of the problem is that I need to change the permit section in my controller to reflect that I am passing a hash/array. If I look at the resulting record, the 2 fields that I am setting as multi-selects show as nil. However, if I force an errror, the parameters shown by rails show the correct choices. therefore, I believe that the problem might be with the permit section.
That looks like
*def search_params
params.require(:search).permit(:document_title,
:summary,
:owner,
:category,
:file_name,
:doc_to_email,
:categories_attributes => [:name])
end*
I added the :categories_attributes => [:name] to try to get the controller to allow hashes but that didn't work.
The select field is
<%= f.select :category[], options_for_select(#categories.sort), {:include_blank => true}, {:multiple => true, :size =>10} %>
but that gives me
.erb where line #41 raised:
wrong number of arguments (0 for 1..2) Trace of template inclusion:
app/views/searches/new.html.erb
I thought I had to set category as an array with the [] but obviously I'm missing something.
Category is a string field in the Searches table.
You do not need the [] brackets after the field name as Rails adds those in automatically.
See the example here:
http://apidock.com/rails/ActionView/Helpers/FormTagHelper/select_tag
select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>".html_safe, multiple: true
# => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option>
# <option>Green</option><option>Blue</option></select>
In your case the selected values will be available as an array in params[:search][:category] after the form is submitted.
If you use strong parameters, also make sure you have :category => [] in the permit list.
I have a select box for the event types of an event. event belongs to event_type and event_type has many events. Here's what I have for the select box:
<%= f.select :event_type, options_from_collection_for_select(EventType.all, :id, :name, #event.id), :placeholder => 'Select an event type' %>
But, the problem is that when I submit it, it submits the id of the event type and not the name of it. So, how would I make it submit the name rather than the id? If you need to see the any more code than just tell me, thanks
The second parameter to options_from_collection_for_select is the value that will be submitted with the form. You have :id, so change it to :name.
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select
(but this seems like a strange thing to do - typically you would store the event type ID.)
You can use the id after the submit to load the event type again in your controller post action like this:
selected_type = EventType.find(params[:event_type]
It is also a good practice to keep database calls to the controller, so please put the EventType.all statement in there and pass it as local or class variable like you did with event.
If you really want to pass the name in your form instead of the id, you can replace the :id part in your call to something more like this options_from_collection_for_select(#event_types, :name, :name, #event.event_type.name). Keep in mind that this value should be unique!
The method works like this:
options_from_collection_for_select(collection, value_method, text_method, selected = nil)
So the first parameter contains all the options, the second defines the value within those option objects which are put into the value field of the HTML option (which is being submitted by the form), the third defines the text which is displayed to the user and the final parameter defines the value of the selected entry (in case you are editing an entry for example). For the last parameter, you need to use the events' event_type id, or in your case, the name because you set the value of your HTML tag to it.
Use pages like ApiDock or the Rails tutorials to get examples for some of these methods.
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select
You should pass name in the Value method, if you want to pass the name,
<%= f.select :event_type, options_from_collection_for_select(EventType.all, :name, :name, #event.id), :placeholder => 'Select an event type' %>
Here is the doc for options_from_collection_for_select
I am going through the Rails API docs for collection_select and they are god-awful.
The heading is this:
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
And this is the only sample code they give:
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, :prompt => true)
Can someone explain, using a simple association (say a User has_many Plans, and a Plan belongs to a User), what I want to use in the syntax and why?
Edit 1: Also, it would be awesome if you explained how it works inside a form_helper or a regular form. Imagine you are explaining this to a web developer that understands web development, but is 'relatively new' to Rails. How would you explain it?
collection_select(
:post, # field namespace
:author_id, # field name
# result of these two params will be: <select name="post[author_id]">...
# then you should specify some collection or array of rows.
# It can be Author.where(..).order(..) or something like that.
# In your example it is:
Author.all,
# then you should specify methods for generating options
:id, # this is name of method that will be called for every row, result will be set as key
:name_with_initial, # this is name of method that will be called for every row, result will be set as value
# as a result, every option will be generated by the following rule:
# <option value=#{author.id}>#{author.name_with_initial}</option>
# 'author' is an element in the collection or array
:prompt => true # then you can specify some params. You can find them in the docs.
)
Or your example can be represented as the following code:
<select name="post[author_id]">
<% Author.all.each do |author| %>
<option value="<%= author.id %>"><%= author.name_with_initial %></option>
<% end %>
</select>
This isn't documented in the FormBuilder, but in the FormOptionsHelper
I've spent quite some time on the permutations of the select tags myself.
collection_select builds a select tag from a collection of objects. Keeping this in mind,
object : Name of the object. This is used to generate the name of the tag, and is used to generate the selected value. This can be an actual object, or a symbol - in the latter case, the instance variable of that name is looked for in the binding of the ActionController (that is, :post looks for an instance var called #post in your controller.)
method : Name of the method. This is used to generate the name of the tag.. In other words, the attribute of the object you are trying to get from the select
collection : The collection of objects
value_method : For each object in the collection, this method is used for value
text_method : For each object in the collection, this method is used for display text
Optional Parameters:
options : Options that you can pass. These are documented here, under the heading Options.
html_options : Whatever is passed here, is simply added to the generated html tag. If you want to supply a class, id, or any other attribute, it goes here.
Your association could be written as:
collection_select(:user, :plan_ids, Plan.all, :id, :name, {:prompt => true, :multiple=>true })
With regards to using form_for, again in very simple terms, for all tags that come within the form_for, eg. f.text_field, you dont need to supply the first (object) parameter. This is taken from the form_for syntax.
So over the last 2 hours, I've been trying to fill a combobox with all my users. I managed to get all firstnames in a combobox, but I want their full name in the combobox. No problem you would think, just concatenate the names and you're done. + and << should be the concatenation operator to do this.So this is my code:
<%= collection_select(:user, :user_id, #users, :user_id, :user_firstname + :user_lastname, {:prompt => false}) %>
But it seems RoR doesn't accept this:
undefined method `+' for :user_firstname:Symbol
What am I doing wrong?
What you need to do is define a method on the User model that does this concatenation for you. Symbols can't be concatenated. So to your user model, add this function:
def name
"#{self.first_name} #{self.last_name}"
end
then change the code in the view to this:
<%= collection_select(:user, :user_id, #users, :user_id, :name, {:prompt => false}) %>
Should do the trick.
This isn't really rails giving you an error, it's ruby. You're trying to combine the symbols :user_firstname and :user_lastname
A symbol is a variable type, just like integer, string, or datetime (Well technically they're classes, but in this context we can think of them as variable types). They look similar to strings, and can function similarly to them, but there is no definition for the behavior of symbol concatenation. Essentially you're trying to send the method user_firstnameuser_lastname which is just as non-sensical as trying to concat two Symbols.
What you need to understand is that this parameter is looking for a method on your User object, and it won't understand the combination of two symbols. You need to define a method in your model:
def fullname
[user_firstname, user_lastname].reject{|v| v.blank?}.join(" ")
end
This'll return your first + last name for you, and then in the parameter you should send :fullname (because that's the method it'll call on each user object in the collection):
<%= collection_select(:user, :user_id, #users, :user_id, :fullname, {:prompt => false})%>
Also, it's considered poor practice to prefix every single column with the table name. user.user_firstname just looks redundant. I prefer to drop that prefix, but I guess it's mostly up to personal preference.
The arguments for value and display attribute are method names, not expressions on a user object.
To control the format more precisely, you can use the select tag helper instead:
select("user", "user_id", #users.each {|u| [ "#{u.first_name u.last_name}", u.user_id ] })
The docs are pretty useful.