在简单格式 select 框中设置特定的 selected 值

Setting a specific selected value in a Simple Form select box

我有一个 select 框,里面装满了特定相册类型的选项:

<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` 参数的最佳方法是什么?

你可以这样做:

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

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

编辑

你说得对 - 我查看了源代码,优先级与特定的 :country:time_zone 输入相关联。为了得到你想要的东西,你要么必须找出你想要优先考虑的collection哪个id,要么你可以做一个custom input并实现优先级代码为这两个输入所做的方式的功能。我想这取决于你的需要。 returns id 的助手可能是寻求简单解决方案的方法。

同意之前的答案是理想的。与此同时,我会使用助手:

<%= 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