【问题标题】:Rails country-state_select gem javascript not workingRails country-state_select gem javascript不工作
【发布时间】:2019-12-08 09:46:35
【问题描述】:

安装 country_state_select gem 后,它成功加载了国家,但我选择的第一个国家加载了相应的国家,但在选择另一个国家后,其相应的国家不会加载,而是属于我最后选择的国家的国家。我曾多次尝试关闭服务器以重置它,但仍然会这样做。

<%= simple_form_for(@office_item) do |f| %>
  <%= f.error_notification %>
  <%= f.error_notification message: f.object.errors[:base].to_sentence if 
  f.object.errors[:base].present? %>

<div class="form-inputs">
  <%= f.file_field :pictures, multiple:true %>
  <%= f.input :title %>
  <%= f.input :description %>
  <%= f.association :category, label_method: :title, value_method: :id, 
      include_blank: false, prompt: "Select Category" %>
  <%= f.input :address %>
  <%= f.input :country, collection: CountryStateSelect.countries_collection  
      %>
  <%= f.input :state, CountryStateSelect.state_options(label: "State / 
      Province", form: f, field_names: { :country => :country, :state => 
      :state  } ) %>
  <%= f.input :city, CountryStateSelect.city_options(label: "City ", 
      form: f, field_names: {  :state => :state, :city => :city } ) %>

  <%= f.input :pricing, label: "Price" %>
  <%= f.input :terms, label: "Terms and Conditions" %>
  <%= f.input :is_active, label: "Publish" %>
</div>

<div class="form-actions">
  <%= f.button :submit, class: "btn btn-secondary" %>
</div>
 <% end %>




<script>
   $(document).on('ready page:load', function() {
   return CountryStateSelect({
   country_id: "country",
   state_id: "state"
   city_id: "city"
   });
   });
</script>

我的期望是每个选择的国家都会分别加载其对应的州和城市

【问题讨论】:

  • 控制台有错误吗?
  • 感谢您的帮助。这是我在控制台上发现的错误:Uncaught SyntaxError: Unexpected identifier on city_id: "city" in the console。我在它之后添加了一个昏迷,错误消失了。但是,对所选国家/地区的相应州和城市的选择不起作用。
  • 您在尝试选择其他国家/地区时是否遇到任何新错误?

标签: ruby-on-rails rubygems ruby-on-rails-5


【解决方案1】:
  1. 这个 gem 文档有点过时了,所以当你使用 Rails 5 时,第一行应该是 script

    $(document).on('turbolinks:load', function() {
    

    或者干脆

    $(function() {
    
  2. 然后重新加载页面并查看浏览器的控制台。如果您看到CountryStateSelect is not defined 错误,您应该将gem 的javascript 资产添加到您的application.js 文件中

    //= require country_state_select
    
  3. 您还应该确保您使用的是right ids of &lt;select&gt; 元素

  4. 此 gem 在更改 &lt;select&gt; 值时使用 POST JSON 请求,因此如果您将获得带有 Can't verify CSRF token authenticity.422 Unprocessable Entity,您可以通过添加到您的 ApplicationController 类来禁用此验证

    class ApplicationController < ActionController::Base
      protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
    end
    

【讨论】:

  • @Geni 如果我的回答真的很有帮助,请也投票支持
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多