Using country_select gem with form_tag and no mode

2019-07-24 17:01发布

问题:

I am using the country_select gem in Rails 4 in a form tag:

<%= form_tag(@url, method: :post, class: "form-horizontal") do %>
    <div class="form-group">
      <%= label_tag(:country_code, "Country code") %>
      <%= country_select :country_code, @country_code, class: "form-control" %>
    </div><% end %>

I am getting the following error.

undefined method `NZ' for "NZ":String

This is a quiet unusual error and I have not found any other instances of it for the country_select gem. The rails application does not have a database and is communicating to an external database so there are no models in this application. I have been suggested to use Open Struct to get around this issue. However, I am wondering does anyone know of a quicker fix? The form is picking up the data in the database though!

回答1:

Since you've probably got the country_select gem in your app you also have the countries gem as it is a dependency of country_select. So you could just used the plain Rails form helpers select_tag and options_for_select using the countries gem like this:

select_tag :country, options_for_select(ISO3166::Country.all, params[:country])

Which is a much better choice than using OpenStruct to do this.

See for details and other finders you can use instead of ISO3166::Country.all https://github.com/hexorx/countries



回答2:

The issue was with the fact that I had no model. I needed to use the OpenStruct data structure which helped me to simulate objects. You can read more about it here