【问题标题】:Setting a specific selected value in a Simple Form select box在简单表单选择框中设置特定的选定值
【发布时间】:2015-09-08 15:12:41
【问题描述】:

我有一个选择框,其中包含特定专辑类型的选项:

<select class="select optional" name="album[album_type_id]" id="album_album_type_id">
  <option value="1">Collaborative Album</option>
  <option selected="selected" value="2">Compilation Album</option>
  <option value="2">EP</option>
  <option value="3">Soundtrack</option>
  <option value="4">Studio Album</option>
</select>

我想将Studio Album 设置为默认值。我知道我可以执行以下操作:

<%= f.input :album_type_id, as: :select, collection: @album_types, selected: 4 %>

但将来肯定会添加更多专辑类型,并且更愿意针对它的字符串文字标题。将其用于 SimpleForms 'selected` 参数的最佳方法是什么?

【问题讨论】:

  • 专辑类型是否从数据库中填充?还是硬编码的 HTML?
  • 从数据库中填充。编写 html 输出只是为了让读者了解事物是如何呈现的。

标签: ruby-on-rails forms drop-down-menu default simple-form


【解决方案1】:

同意以前的答案是理想的。同时,我会使用一个助手:

<%= f.input :album_type_id, as: :select, collection: @album_types, selected: get_index_by_name(@albums, 'Studio Album') %>

然后在 helpers/album_helper.rb 中:

module AlbumHelper
  def get_index_by_name(albums, name)
    albums.first { |album| album.name == name }.id
  end 
end


或者因为它是一个实例变量,你可以这样做,但它可能不太可重用:

<%= f.input :album_type_id, as: :select, collection: @album_types, selected: get_album_index_of('Studio Album') %>

然后是助手:

module AlbumHelper
  def get_album_index_of(name)
    @albums.first { |album| album.name == name }.id
  end 
end


如果还有其他下拉菜单,也许可以在整个网站上使用通用的:

<%= f.input :album_type_id, as: :select, collection: @album_types, selected: get_index_by_attribute(@albums, :name, 'Studio Album') %>

在 application_helper.rb 中:

module ApplicationHelper
  def get_index_by_attribute(collection, attribute, value)
    collection.first { |item| item.send(attribute) == value }.id
  end 
end

【讨论】:

  • 感谢您展示无数的解决方案。从来不知道代码块可以在first() 方法中传递。
【解决方案2】:

你可以这样做:

<%= f.input :album_type_id, as: :select, priority: ['Studio Album'], collection: @album_types %>

我现在无法对其进行测试,但我知道国家/地区的集合可以像上面那样优先考虑(甚至在 documentation 中)。我不明白为什么它不适用于您的特定场景。

编辑

您是对的 - 我查看了源代码,优先级与特定的 :country:time_zone 输入相关联。为了得到你想要的,你要么必须找出哪个 id 是你想要优先处理的集合,或者你可以创建一个 custom input 并按照代码为那些执行的方式实现优先级功能两个输入。我想这取决于你的需求。返回id 的助手可能是寻求简单解决方案的方法。

【讨论】:

  • 这产生了一个非常棒的拉取请求——把这个功能分开是没有意义的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-27
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
  • 2020-07-30
相关资源
最近更新 更多