简体   繁体   English

带有Rails 3.1和Ajax的Dynamic Dropdown的错误404(Jquery)

[英]Error 404 for Dynamic Dropdown with rails 3.1 and Ajax (Jquery)

I am having trouble on creating dynamic dropdowns where: 我在创建动态下拉列表时遇到麻烦:

When you select a country, it renders the partial with cities that belong to a country. 选择国家/地区后,它将使用属于某个国家/地区的城市渲染局部视图。

I have the models Country has_many cities and City belongs_to Country 我有模型国家has_许多城市和城市所属国家

With firebug I get an Error when fetching the controller action update_city_select, where it selects a Contact record instead of Country record. 使用萤火虫时,在获取控制器操作update_city_select时会出现错误,它在其中选择联系人记录而不是国家记录。

I followed the example from Peter Mac 我遵循了Peter Mac的示例

Here is my code: 这是我的代码:

application.js application.js

jQuery(function($) {
// when the #region_id field changes
  $("#contact_country_id").live('change', function() {
    // make a POST call and replace the content
    var country = $('select#contact_country_id :selected').val();
    if(country == "") country="0";
    jQuery.get('/contacts/update_city_select/' + country, function(data){
        $("#cities").html(data);
    })
    return false;
  });
})

contacts_controller.rb contacts_controller.rb

  def new
    @contact = Contact.new
    @industries = Industry.all
    @countries = Country.all
    @cities = City.where(["country_id = ?", 1]).all
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @contact }
    end
  end
.
.
.
  def update_city_select
      @cities = City.where(:country_id => params[:id]).order(:name) unless params[:id].blank?
      render :partial => "cities", :locals => { :cities => @cities }
  end

contacts/_form.html.erb contacts / _form.html.erb

<%= form_for(@contact) do |f| %>
...
    <div class="field">
        <%= f.label :country %>
        <%= f.collection_select :country_id, @countries, :id, :name, :prompt => "-- Select a country --" %>
    </div>
    <div id="cities" class="field">
        <%= render 'cities' %>
    </div>
...
<% end %>

contacts/_cities.html.erb contact / _cities.html.erb

<%= fields_for @contact do |f| %>
    <%= f.label :city %>
    <% unless cities.blank? %>
        <%= f.collection_select :city_id, cities, :id, :name, :prompt => "-- Select a city --" %>
    <% else %>
        <%= f.select "city_id","city_id", :prompt => "-- Select a city --" %>
    <% end %>

<% end %>

routes.rb routes.rb

  resources :cities
  resources :countries
  resources :contacts
  get '/contacts/update_city_select/:id' => 'contacts#update_city_select'

You're help on solving this Ajax problem would be most appreciated! 非常感谢您对解决此Ajax问题的帮助!

Aurelien 奥雷利安

The problem: 问题:

From the tutorial as mentioned above, I thought I had to have the method "update_city_select" in the Contacts controller. 从上面提到的教程中,我认为我必须在Contacts控制器中使用方法“ update_city_select”。 The routing then thought it should fetch an item from the Contact records instead of a Country record. 然后,路由认为它应该从联系人记录而不是国家记录中获取项目。

The solution: 解决方案:

The solution for displaying the Ajax correctly me was 1) to nest countries resources, 2) move the method to the countries controller, 3) create a partial "_cities.html.erb" in the countries views, 4) slightly modify the form and the JS. 为我正确显示Ajax的解决方案是1)嵌套国家资源,2)将方法移至国家控制器,3)在国家视图中创建部分“ _cities.html.erb”,4)略微修改表单,然后JS。

I posted below the entire code for those who might run into similar problems or need an answer on how to have the dynamic select work. 我在完整的代码下面贴了一些可能会遇到类似问题或需要如何进行动态选择工作的答案的人。

Note: I use rails 3.1 with JQuery and NO form builder or formstatic gems 注意:我将Rails 3.1与JQuery和NO form builder或formstatic gem一起使用

The models 型号

class Contact < ActiveRecord::Base
  belongs_to :city
  belongs_to :country

  attr_accessible :name, :country_id, :city_id
end

class Country < ActiveRecord::Base
  has_many :cities, :dependent => :destroy
  has_many :contacts
  attr_accessible :name, :city_id
end

class City < ActiveRecord::Base
  has_many :contacts
  belongs_to :country
  attr_accessible :name, :country_id
end

For the controllers , just create a regular restful format and just add to the countries_controller the following method 对于控制器 ,只需创建常规的restful格式,然后将以下方法添加到countries_controller

def update_city_select
    @cities = City.where( :country_id => params[:id]).order(:name) unless params[:id].blank?
    render :partial => "cities", :locals => { :cities => @cities }
end

For the "Views/contacts/new.html.erb" you will need 2 things: to include a collection_select for the countries and to refer to a partial that will be placed as "views/countries/_cities.html.erb" . 对于“ Views / contacts / new.html.erb”,您需要做两件事:为国家/地区添加collection_select ,并引用将放置为“ views / countries / _cities.html.erb”的部分 I also have a duplicate of the _cities partial within the contacts views. 我在联系人视图中也有_cities部分的副本。

views/contacts/new.html.erb views / contacts / new.html.erb

<%= form_for(@contact) do |f| %>
    <div class="field">
        <%= f.label :country %>
        <%= f.collection_select :country_id, @countries, :id, :name, :prompt => "-- Select a country --" %>
    </div>
    <div id="cities" class="field">
        <%= render 'cities' %>
    </div>
<% end %>

views/countries/_cities.html.erb views / countries / _cities.html.erb

<%= label_tag :city %>
<% unless @cities.blank? %>
    <%= collection_select(:contact, :city_id, @cities, :id, :name, :prompt => true )%>
<% else %>
    <%= select_tag "city_id","city_id", :prompt => "-- Select a city --" %>
<% end %>

Then create Ajax call in your application.js file 然后在application.js文件中创建Ajax调用

jQuery(function($) {
// when the #region_id field changes
  $("#contact_country_id").live('change', function() {
    // make a POST call and replace the content
    var country = $('select#contact_country_id :selected').val();
    if(country == "") country="0";
    jQuery.get('/countries/update_city_select/' + country, function(data){
        $("#cities").html(data);
    })
    return false;
  });
})

The final cycle is to make sure you can access the Countries resources from Contact form. 最后一个周期是确保您可以从“联系人”表单访问“国家”资源。 In order to do so, you just need to nest your Countries resources within the Contact resources. 为此,您只需要在联系资源中嵌套“国家”资源。 You will also need to make Get request call for your update_city_select as so: 您还需要为update_city_select发出Get请求调用,如下所示:

routes.rb
resources :cities
resources :countries
resources :contacts do
  resources :countries
end

get '/countries/update_city_select/:id' => 'countries#update_city_select'

Thank you for the support Baldrick and volodymyr 感谢您对Baldrick和volodymyr的支持

Aurelien 奥雷利安

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM