Question

I am using the best_in_place gem to edit records inline and country_select to render a list of countries to select from. When using best_in_place to edit a select field i do this:

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

Now i like to get a list of all the countries that country_select has and pass that into the collection parameter. The country_select gem provides a simple helper to render the select field:

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

I would like to replace the :collection parameter in best_in_place helper to include the list of countries provided by country_select. I know that best_in_place expects the [[key, value], [key, value],...] input into :collection, but i am not sure how to do this. Please advise. Thanks

Was it helpful?

Solution

Just do the following and it will work:

<%= best_in_place @home, :country, type: :select, collection: (ActionView::Helpers::FormOptionsHelper::COUNTRIES.zip(ActionView::Helpers::FormOptionsHelper::COUNTRIES)) %>

OTHER TIPS

If you are using rails 4 a few years later , this does the trick:

<%= best_in_place @cart.order, :country_name, type: :select, :collection =>  ActionView::Helpers::FormOptionsHelper::COUNTRIES%>

In Rails 5.2, assuming you have the Countries gem, you should do:

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

The fix_for_bip is a custom function I've inserted into the Array class, because best_in_place requires all select box arrays to be served in the opposite order from regular select boxes: for a regular Rails select, you'd give an array of [["Spain", "ES"], ["Sri Lanka", "SR"], ["Sudan", "SD"]...] (first what the user sees, then the option value). So this is what the Countries gem returns. However, best_in_place collection: only accepts the reverse kind of array: [["ES", "Spain"], ["SR", "Sri Lanka"], ["SD", "Sudan"]]. It also has a problem when not all array items are themselves two-item arrays - something that Rails select boxes deal with automatically. So I created a fix_for_bip function that I call on all of my arrays when feeding them to best_in_place:

class Array
  def fix_for_bip
    self.map { |e| e.is_a?(Array) ? e.reverse : [e, e] }
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top