Ruby on Rails中的动态选择菜单

时间:2015-09-30 14:12:24

标签: ruby-on-rails ajax

提前感谢任何尝试或回答我的问题的人。 我有City模型,Area模型,User模型。 City模型和Area模型具有" has_many"协会 其中区域模型和用户模型具有许多通过"协会

我希望区域选择菜单显示根据所选城市,创建新用户时 当选择城市选择菜单中的任何项目(发出ajax请求)时,区域选择菜单应显示属于该城市的区域。

这是我的代码,请告诉我哪里错了。 (谢谢)

(app/views/users/_form)
<%= form_for(@user, remote: true) do |f| %>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
<p>
<%=f.collection_select :city_id, City.order(:name), :id, :name, include_blank: true%>
</p>

<div class="a"></div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

(应用程序/控制器/ users_controller.rb)

    class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]

    def custom
        @tilu = params[:city_id]
      respond_to do |format|
        format.js
      end
    end
  # GET /users
  # GET /users.json
  def index
    @users = User.all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = User.new
    @areas= Area.all
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
    before_action :get_area, only:[:create]
  def create
    @user = User.new(user_params)

      @user.area_ids = @area

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end
    def get_area
        @area = params[:user][:area_id]
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
        params.require(:user).permit(:name, :description,[:area_id])
    end
end

(应用程序/资产/ Javascript角/ users.js.coffe)

jQuery ->
  $(document).on 'change', '#user_city_id', (evt) ->
    $.ajax '/users/custom',
      type: 'GET'
      dataType: 'html'
      data: {
        city_id: $('#user_city_id :selected').val()
      }
      error: (jqXHR, textStatus, errorThrown) ->
        console.log("AJAX Error: #{textStatus}")
      success: (data, textStatus, jqXHR) ->
        console.log("Dynamic country select OK!")

(配置/ routes.rb中)

Rails.application.routes.draw do
  resources :users
  resources :areas
  resources :cities
    get 'users/custom'

(应用/视图/用户/ _customTemplate.html.erb)

<%=f.collection_select :area_id, Area.where(city_id: @tilu), :id, :name, include_blank: true %>

最后但并非最不重要...... (应用/视图/用户/ custom.js.erb)

$('.a').append("<%=j render 'customTemplate' %>");

帮助!

ruby​​服务器控制台错误

  

开始GET&#34; / users / custom?city_id = 1&#34;在2015-09-30发表于127.0.0.1   21:20:01 +0530由UsersController处理#show as HTML
  参数:{&#34; city_id&#34; =&gt;&#34; 1&#34;,&#34; id&#34; =&gt;&#34;自定义&#34;}用户负载(0.3ms)   SELECT&#34;用户&#34;。* FROM&#34;用户&#34;用户&#34;。&#34; id&#34; =?限制1 [[&#34; id&#34;,   0]]在76ms内找不到404(ActiveRecord:0.3ms)

     

ActiveRecord :: RecordNotFound(找不到用户&#39; id&#39; =自定义):
  app / controllers / users_controller.rb:77:在`set_user&#39;

     

渲染   /usr/local/lib/ruby/gems/2.2.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_source.erb   (4.1ms)

浏览器控制台错误

  

获取http://localhost:3000/users/custom?city_id=1 404(未找到)发送@   ?jquery的-4075e3b7b3964707c653f61b66f46dec.js体= 1:9665jQuery.extend.ajax   @ jquery-4075e3b7b3964707c653f61b66f46dec.js?body = 1:9216(匿名   功能)@   ?用户-c743c610a872f962fb75a7ac244905cd.js体= 1:4jQuery.event.dispatch   @   ?jquery的-4075e3b7b3964707c653f61b66f46dec.js体= 1:4671elemData.handle   @   ?jquery的-4075e3b7b3964707c653f61b66f46dec.js体= 1:4339ListPicker._handleMouseUp   @ about:blank:544 users-c743c610a872f962fb75a7ac244905cd.js?body = 1:11   AJAX错误:错误

2 个答案:

答案 0 :(得分:2)

好的,我有太多的问题需要通过它们来解决;这就是我要做的事情:

您正在寻找名为dynamic select menus的内容。你在标题中提到这一点,我只想澄清术语。

当您更改选择框中的值时,动态选择菜单应发送ajax请求。这个过程应该简洁(IE只向你的控制器发送ID),最后你得到一组返回的数据来填充下一个选择框:

#config/routes.rb
resources :cities do
    get "update", to: "users#custom" #-> url.com/cities/:city_id/update
end
resources :users #-> put this below so that the users/show method doesn't catch the above calls

#app/controllers/users_controller.rb
class UsersController < ApplicationController
   def custom
      @city = City.find params[:city_id]
      respond_to do |format|
        format.js
      end
   end
end

#app/views/users/custom.coffee
$('.a').append("<%=j render 'users/customTemplate' %>");

以上是“后端”。这是“前端”:

#app/views/users/_form.html.erb (removed HTML to clean it up for this)
<%= form_for(@user, remote: true) do |f| %>
    <%= f.text_field :name %>
    <%= f.collection_select :city_id, City.order(:name), :id, :name, include_blank: true %>
    <%= f.submit %>
<% end %>

#app/assets/javascripts/users.coffee
$(document).on 'change', '#user_city_id', (evt) ->
    $.ajax '/cities/' + $(this).val() + '/update',
      type: 'GET'
      dataType: 'html'
      data: {
        city_id: $('#user_city_id :selected').val()
      }
      error: (jqXHR, textStatus, errorThrown) ->
        console.log("AJAX Error: #{textStatus}")
      success: (data, textStatus, jqXHR) ->
        console.log("Dynamic country select OK!")

通过观看Railscast

,您将获得很多收获

enter image description here

答案 1 :(得分:0)

这个例子对我有用..但是我必须将我的colection_select转换为仅选择,但从来没有更少的工作,并感谢所有试图解决问题的人

[1]: https://kernelgarden.wordpress.com/2014/02/26/dynamic-select-boxes-in-rails-4/