I want to select a specific value in the collection_select, how do I?

Asked

Viewed 112 times

1

Good morning, I’m working with Ruby on Rails and I’m having a little trouble. I have a value in a @n variable, and I have a collection_select that will fetch me all the values of a collection. what I want to do is to select the value that is in the @n variable. the value that is in @n is "Cats". i have: <%= f.collection_select :isolated_id, @isolateds, :id, :name, prompt: true %> where @isolateds is my collection that includes the name "Cats".

When I go to see the code in html I have:

<select id="resist_isolated_id" name="resist[isolated_id]">
      <option value="">Please select</option>
      <option value="1">cenas</option>
      ...
      <option value="22">cats</option>
</select>

I wanted to: <option value="22" selected="selected">cats</option> and if in the collection :selected => 22 he does this to me, the problem is that if it’s any other name, other than "Cats", I won’t know from the start what is its corresponding "value", so I wanted to pass directly the @n variable but when I do :selected => "@n", nothing. Someone can help me?

1 answer

0


Selected works with value, not text, in your case @n should have "22" as content, so it would work.

  • Because, my problem is that I really have to work with the text, there is some way, or there is some way to put the value equal to the text?

  • <%= f. collection_select :isolated_id, @isolateds, :id, :name, prompt: true %> Instead of :id, you can put :name.

  • Thank you so much :)

  • Just one more question, how do I get disable, next to :Selected => "#{@n}" I’m putting :disable => "disable" and you’re not giving me.

  • See if you can solve your problem: http://stackoverflow.com/questions/23819157/how-to-make-a-collection-select-disabled-in-rails-4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.