0

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 ?

captainrad
  • 3,760
  • 16
  • 41
  • 74

2 Answers2

0

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.

  1. 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.

  2. 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.

  3. If neither of these are feasible or make sense, go ahead and use the JSON encoded form values.

Community
  • 1
  • 1
yez
  • 2,368
  • 9
  • 15
0

Try this

<%= f.select :entity_id,
            options_from_collection_for_select(@entities, :id, :name, entities),
            {},
            {
              data: { placeholder: "Choose entity..." },
              multiple: true
            } %>