【问题标题】:Ruby on Rails - select option helperRuby on Rails - 选择选项助手
【发布时间】:2023-03-22 01:44:01
【问题描述】:

有人可以帮忙选择助手吗,因为我是 Ruby On rails 的新手。

我有一个json对象如下,

@response = {"status" => "200", "fruit" => [ {
    "id" => 1,
    "name" => "Apple"
  }, {
    "id" => 2,
    "name" => "Mango"
  } ]
}

我在助手中返回值“return @response['rateCard']” 现在我希望这个助手在视图文件中生成这样的代码,这样它就会有类似的选择框

<select name='fruit'>
<option value="1">apple</option>
<option value="2" selected>mango</option>
</select>

请帮忙

实际上我有一个助手“Fruits_helper.rb”正在返回

def selFruit
    @resp = Fruit.getFruit # this will return @response object as mentioned above

    return @resp['fruit']
end

================================================ ==================================== 所以在我的fruit.html.erb 文件中,我有如下一小段代码

<%= form_for(:AdminLogin) do |f| %>
<div>

<%= select_tag "fruit", options_for_select(selFruit.each{|fruit,key| [fruit[key]=>'name',fruit[key]=>'id']}) %>

<div>
<% end %>

================================================ ============================== 上面的代码给了我 o/p as

<select name="fruit" id="fruit">
<option value="id1nameApple">id1nameApple</option>
<option value="id2nameMango">id2nameMango</option>
</select>

我想要的结果是苹果

【问题讨论】:

  • form_for -> form.select,而不是 select_tag。 selFruit.each -> selFruit.map

标签: ruby-on-rails ruby select helper


【解决方案1】:

我的问题已经通过以下代码解决了,希望它也能帮助其他 RoR 新生

<%= select_tag "fruit", options_for_select(selFruit.map{|fruit,key| [fruit['name'], fruit['id']]}) %>

【讨论】:

  • 使用form_for 的表单构建form.select 是标准方式。
【解决方案2】:

如果您使用(并且应该)form_for builder:

form.select(:fruit, @response["fruit"].map { |f| [f["name"], f["id"]] })

【讨论】:

  • 以上代码向我抛出错误,因为“参数数量错误(2 代表 0)”
猜你喜欢
  • 1970-01-01
  • 2011-05-27
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 2015-12-10
  • 2011-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多