开发者

RoR select tag options

My model is given below

class Question < ActiveRecord::Base
  ANSWERS= ['Option 1', 'Option 2', 'Option 3', 'Option 4']
end

In the view <%= select(:question, :answer, Question::ANSWERS, {:include_blank => true}) %> outputs

<select name="question[answer]" id="question_answer">
  <option value=""></option>
  <option value="Option 1">Option 1</option>
  <option value="Option 2">Option 2</option>
  <option value="Option 3">Option 3</option>
  <option value="Option 4">Option 4</option>
</select>

I tried <%= select(:question, :answer, Question::ANSWERS.collect {|d| [d, Question::ANSWERS.index(d)]}, {:include_blank => true}) %> This yields

<select name="question[answer]" id="question_answer">
  <option value=""></option>
  <option value="0">Option 1</option>
  <option value="1">Option 2</option>
  <option value="2">Option 3</开发者_开发问答option>
  <option value="3">Option 4</option>
</select>

But I need the following output

<select name="question[answer]" id="question_answer">
  <option value=""></option>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
</select>


In your second example, use:

<%= select(:question, 
           :answer, 
           Question::ANSWERS.collect {|d| [d, Question::ANSWERS.index(d) + 1]},
           {:include_blank => true}) %>


You can little modify your array with key value pair of hash like this

ANSWERS= [1=>'Option 1', 2=>'Option 2', 3=>'Option 3', 4=>'Option 4']

Now use options_for_select and get desired output.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜