使用 country_select gem 和 form_tag 并且没有模型

Using country_select gem with form_tag and no model

我在 Rails 4 中使用 country_select gem 表单标签:

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

我收到以下错误。

undefined method `NZ' for "NZ":String

这是一个安静的异常错误,我还没有为 country_select gem 找到任何其他实例。 rails 应用程序没有数据库并且正在与外部数据库通信,因此此应用程序中没有模型。有人建议我使用 Open Struct 来解决这个问题。但是,我想知道是否有人知道更快的修复方法?表单正在获取数据库中的数据!

问题在于我没有模型。我需要使用 OpenStruct 数据结构来帮助我模拟对象。您可以阅读更多相关信息 here

由于您的应用程序中可能有 country_select gem,因此您也有 countries gem,因为它是 country_select 的依赖项.所以你可以使用普通的 Rails 表单助手 select_tagoptions_for_select 使用 countries gem 像这样:

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

与使用 OpenStruct 相比,这是一个更好的选择。

有关详细信息和您可以使用的其他查找器,请参阅 ISO3166::Country.all https://github.com/hexorx/countries