在Rails中使用js.erb

时间:2019-01-08 07:13:49

标签: ruby-on-rails ruby

在带有devise的Rails 5应用程序中,我需要使用一个new.js.erb文件来更新注册视图和控制器中的select标签。我似乎无法弄清楚为什么我的new.js.erb文件无法正常工作。

我尝试如下在控制器中使用respond_to

registrations-controller.rb

 def new
   super 
   @cities = CS.get(:us,params[:state]) 
   respond_to do |format|
     format.js { render '/new.js.erb' }# layout: false }          
     format.html 
   end
 end

new.html.erb

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), :remote => true) do |f| %>
   <div class="signup-input-container">
     <div class="field">
        <%= f.text_field :firstname, autofocus: true, autocomplete: "firstname", placeholder: "First name", class: "signup-input-container--input" %>
     </div>
     <div class="field">
        <%= f.select :state, options_for_select(CS.states(:us).map { |code, name| [name, code] }),{:prompt => "State"}, {:class => "signup-input-container--input", :id => "state-picker"} %>
     </div>
     <div class="field">
        <%= f.select :city, options_for_select([]),{}, {:class => "signup-input-container--input", :id => "city-picker"} %> 
     </div>
  </div>
<% end %>

new.js.erb

  var city = document.getElementById("city-picker");

  while (city.firstChild) city.removeChild(city.firstChild);

  var placeholder = document.createElement("option");
  placeholder.text = "Choose a city";
  placeholder.value = "";
  city.appendChild(placeholder);

 <% @cities.each do |c| %>
   city.options[city.options.length] = new Option('<%= c %>');
 <% end %>

main.js

  var state = document.getElementById("state-picker");
  state.addEventListener("change", function() {
     $.ajax({
        url: "/states?state=" + state.value,
        type: "GET"
     })
  })

我希望这可以在控制器中的城市阵列中创建选择标签选项。有谁知道如何使它工作?

1 个答案:

答案 0 :(得分:0)

要解决此问题,您应该只设置一个单独的控制器,您可以在其中异步获取数据,或者还有一些免费的API,可用于地理查询,例如Googles Geocoding APIGeonames

要设置单独的控制器,您可以通过以下方式实现:

# /config/routes.rb
get '/states/:state_id/cities', to: 'cities#index'

# /app/controllers/cities_controller.rb
class CitiesController < ApplicationController
  # GET
  def index
    @cities = CS.get(:us, params[:state_id]) 
    respond_to do |f|
      f.json { render json: @cities }
    end
  end
end

我将完全跳过使用.js.erb模板,只返回可直接在JS或许多现有自动完成解决方案中使用的JSON数据。 .js.erb仅对要重用服务器端模板的广泛HTML模板(例如,渲染整个表单)有意义;它极大地增加了复杂性,并且通常使您的javascript混乱,这不值得输出选项标签列表。

// If you are using jQuery you might as well setup a delegated
// handler that works with turbolinks, 
$(document).on('change', '#state-picker', function(){
  $.getJSON("/states/" + $(this).value() + "/cities", function(data){
    // using a fragment avoids updating the DOM for every iteration.
    var $frag = $('<select>');
    $.each(data, function(city){
      $frag.append$('<option>' + data + '</option>');
    });
    $('#city-picker').empty()
                  .append($('frag').children('option'));
  });
});