3

我正在使用best_in_place gem 在线编辑记录,并使用country_select来呈现可供选择的国家列表。当使用 best_in_place 编辑选择字段时,我这样做:

<%= best_in_place(@home, :country_name, :type => :select, :collection => [[1, "Spain"], [2, "Italy"]]) %>

现在我想获取 country_select 拥有的所有国家/地区的列表,并将其传递到集合参数中。country_select gem 提供了一个简单的助手来呈现选择字段:

<%= country_select("home", "country_name") %>

我想替换 best_in_place 助手中的 :collection 参数以包含由 country_select 提供的国家/地区列表。我知道 best_in_place 期望 [[key, value], [key, value],...] 输入到 :collection 中,但我不知道该怎么做。请指教。谢谢

4

3 回答 3

5

只需执行以下操作,它将起作用:

<%= best_in_place @home, :country, type: :select, collection: (ActionView::Helpers::FormOptionsHelper::COUNTRIES.zip(ActionView::Helpers::FormOptionsHelper::COUNTRIES)) %>
于 2012-06-11T16:27:49.447 回答
0

如果您在几年后使用 rails 4,这可以解决问题:

<%= best_in_place @cart.order, :country_name, type: :select, :collection =>  ActionView::Helpers::FormOptionsHelper::COUNTRIES%>
于 2014-05-19T11:55:26.513 回答
0

在 Rails 5.2 中,假设你有 Country gem,你应该这样做:

<%= best_in_place @home, :country, type: :select, collection: ISO3166::Country.all_names_with_codes.fix_for_bip, place_holder: @home.country %>

fix_for_bip 是我插入到 Array 类中的自定义函数,因为 best_in_place 要求所有选择框数组以与常规选择框相反的顺序提供:对于常规 Rails 选择,您将给出一个数组[["Spain", "ES"], ["Sri Lanka", "SR"], ["Sudan", "SD"]...](首先是什么用户看到,然后是选项值)。所以这就是国家宝石返回的东西。但是,best_in_place collection:只接受反向类型的数组:[["ES", "Spain"], ["SR", "Sri Lanka"], ["SD", "Sudan"]]. 当并非所有数组项本身都是两项数组时,它也会出现问题——Rails 选择框会自动处理这些问题。因此,我创建了一个 fix_for_bip 函数,当将它们提供给 best_in_place 时,我会调用所有数组:

class Array
  def fix_for_bip
    self.map { |e| e.is_a?(Array) ? e.reverse : [e, e] }
  end
end
于 2020-05-07T10:06:14.757 回答