This shouldn't be a problem but I can't figure it out.
Using form helpers I populate a select field like so:
...
<%= f.select(:entity_id, entities.map {|entity| [entity.name, entity.id]}) %>
...
This is to create a User and set their entity_id. After the form submission I now have a new User whose entity_id is now the value of the option from the select field.
For example if I had selected "Store A" as my entity from the select element, the entity_id for that user is now '1' after I submit the form. This is great but I also need the entity_name "Store A" associated with the user.
So instead of my new user returning the following:
#<User name: 'John Doe', entity_id: '1', entity_name: 'Store A'>
I am getting
#<User name: 'John Doe', entity_id: '1', entity_name: nil>
Which makes sense becuase I never set entity_name.
How would I set entity_name in this form based on the selection ?
If I understand your question correctly, it looks like you want to set two values at the same time for a single input box. Rails does not provide a simple way to do this but it seems that this answer is similar to what you want.
However, I'd still ask the question: Why try to do it all on form submission?
You are already setting the entity_id on the User so you have a few options.
Assuming that entities is a relation of ActiveRecord or some other ORM objects, you could let the association do the work. If a user has_one :entity and then needs to know its entity_name then it could look like: user.entity.name after you set the correct entity_id on said user. This leverages the built in relationship framework Rails provides and keeps you from duplicating data.
If entities is not a relation or set of persisted objects, the code you used to generate the form must have known about entities during render time so it stands to reason that you would have access to it again. In the controller that accepts this form, fetch entities the same way you have done previously and link the entity with the submitted entity_id's name to the User you are updating.
If neither of these are feasible or make sense, go ahead and use the JSON encoded form values.
Try this
<%= f.select :entity_id,
options_from_collection_for_select(#entities, :id, :name, entities),
{},
{
data: { placeholder: "Choose entity..." },
multiple: true
} %>
Related
I'm creating a registration form where a user inputs there address details. For the country field, i would like it to be defaulted to "united kingdom', in the database unless specified other wise, but i would like the form input to be blank. At the moment, it currently show "united kingdom' in the form. is it possible to do this?
I've already done the migrations for it. thanks
Per the docs here: https://apidock.com/rails/ActionView/Helpers/FormHelper/text_field
You can specify a value for the field:
<%= text_field :your_model, :country, value: '' %>
Hard to say exactly what you need since you haven't provided any code, but you could add validation that sets the value to 'United Kingdom' if the value of that field is blank?
I'm working on a code base that I'm not very familiar with, specifically Haml. I need to set-up a select dropdown to select a user.
I have the following code in my controller:
def edit
#franchise = Franchise.find params[:id]
#ab_reps = User.where role: "admin-ab"
authorize! :update, #franchise
end
I have the following code in my form (that doesn't currently work):
= f.select :ab_rep, options_for_select(#ab_reps, f.object.ab_rep), {prompt: "AB Representative"}, {label: false, right_class: "col-sm-10", class: "ab-rep-field"}
Couple questions:
1.) #ab_reps is an array of user objects. I have the following method in my user model:
def name
[first_name, last_name].compact.join(" ")
end
How do I get the select to display the user names instead of the user objects (which it currently does) ?
2.) Is my current set-up even close to being correct?
Thanks for your help!
You are close, you need to provide the methods for the option value and the option text, as well as the collection which in your case is #ab_reps. Additionally you can provide a hash for prompts and for html_options such as class names, which you've done.
Rails has a few different helpers you can use for select tags including options_from_collection_for_select. I've used collection_select often, http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select
= f.collection_select :ab_rep, #ab_reps, :id, :name, {prompt: "AB Representative"}
In a Rails app I have a model with a string attribute, that can only accept a short list of possible values.
A gender select is a good example of this:
(using simpleform)
<%= f.input :gender, :collection => [["male"],["female"]], :prompt => "Select" %>
and provides three states, 'male', 'female', and unselected.
In an effort to improve UX, we're replacing this select field with two checkboxes with values of 'male' and 'female', which again provides three options due to some jquery magic.
male / false
false / female
false / false
The problem is, the value of the first checkbox is alway overwritten by the value of the second on form submit.
Now I could do something with jquery on the client side to deal with this, I could also create a method on the server to deal with this. But that is not the purpose of this question.
I've never been confident that I fully understand all of the various features and uses of f.check_box, check_box object and check_box_tag. Is there a clever way to achieve the desired result within a Rails form, or am I on the wrong track?
I'm implementing select2 tagging with a has_many through relationship. My implementation has 2 different scenarios.
The select menu allows multiple (tagging) but does not allow on the fly input into the select menu.
Same as above but uses ajax to allow the user to enter new select values on the fly.
Scenario 1 works well for tagging. Scenario 2 seems to work (can perform tagging) but does not save the values. My problem seems to come down to my my input elements for the scenarios.
Scenario 1 uses:
<%= f.association :repairers, label_method: :rep_name, value_method: :id, include_blank: true, label: 'Repairer'%>
and when the form is submitted gives params similar to:
"repairer_ids"=>["", "1132", "1131"]
Scenario 2 uses:
<%= f.hidden_field :repair_type_id, :class => "required on-the-fly-select select"%>
and uses a lot of js code to implement on the fly input for the select menu. When the form is submitted the data will look like:
"repair_type_id"=>"5688,5690"
So with scenario 2 the ids are not submitted as an array. I have tried changing the select to:
<%= hidden_field_tag("repair_item[repair_type_ids][]", "", :id => "repair_item_repair_type_ids", :class => "required on-the-fly-select select") %>
but then the relevant param is submitted incorrectly and doesn't save:
"repair_type_ids"=>["5688,5690"]
Is it possible to get the params from Scenario 2 to submit in the format that Rails made the params in Scenario 1?
Try String#split
repair_type_id = "5688,5690"
repair_type_id.split(',')
=> ["5688", "5690"]
It's Better to use this split method in controller while saving the data on particular attribute for this instead of on hidden_tag.
Edit:
If you want to convert string in plural then use pluralize same as for singularize
2.0.0-p481 :010 > 'cat'.pluralize
=> "cats"
2.0.0-p481 :011 > 'dogs'.singularize
=> "dog"
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