更改选择时用ajax更改div

时间:2013-08-22 08:54:10

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

更改选择时更新div时遇到问题。

首先,我在这样的视图中创建我的选择。

=collection_select(:department, :id, Department.all, :id, :name, options={:prompt=>"Seleccione departamento"})

现在我创建一个ajax调用来获取select的值并找到匹配的所有日期

:javascript
  $(document).ready(function(){
  $('#department_id').change(function(){
    $.ajax({
      url:"/movements/find_by_department",
      type: "GET",
      data: {valor: $('#department_id').val()}
    });
  });
  })

下一步是创建一个方法“find_by_department”来获取值..并显示一些东西

 def find_by_department
    id_department = (params[:valor])
    @ideas_department = Idea.find_by_department_id(id_department)

    respond_to do |format|
      format.js {render :department_chart}
    end
  end

现在是我的问题,我有一个部分“department_chart”与此

$("#my_id4").html("@ideas_department")

但是id =“my_id4”不会改变

另一方面,我在控制台中看到了这一点

Started GET "/movements/find_by_department?valor=5" for 127.0.0.1 at 2013-08-22 09:50:04 +0100
Processing by MovementsController#show as */*
  Parameters: {"valor"=>"5", "id"=>"find_by_department"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 10 LIMIT 1
  Option Load (0.2ms)  SELECT "options".* FROM "options" WHERE "options"."name" = 'ideas_status_updated_date' LIMIT 1

我不是为什么要调用show方法

我在路由器中有这个

  get 'movements/find_by_department', :as => 'find_by_department'

1 个答案:

答案 0 :(得分:1)

更改您的路线:

resources :movements do
   get 'find_by_department', on: :member      
end

将您的javascript代码更改为:

 :javascript
  $(document).ready(function(){
  $('#department_id').change(function(){
    $.ajax({
      url:"/movements/#{$('#department_id').val()}/find_by_department",
      type: "GET"
    });
  });
  })

在您的控制器中:

def find_by_department
 @ideas_department = Idea.find_by_department_id(params[:id])

 respond_to do |format|
  format.js {render :department_chart}
 end

如果您想根据来自请求的ID更改您的ID,请将您的代码更改为:

$("#my_id#{@ideas_department.id }").html("<%= @ideas_department %>")

希望它会有所帮助。感谢