【发布时间】:2013-12-18 14:21:43
【问题描述】:
我正在尝试构建一个具有三个模型的 RoR 应用程序:
- 游戏可以分为一个扇区(称为 GameSector)和一个子扇区(称为 GameSubsector)
- 一个部门由许多子部门组成。
- 一个子部门。
这是我的基本模型关系:
models/game.rb
belongs_to :game_sector, :foreign_key => 'game_sector_id', :counter_cache => true
belongs_to :game_subsector, :foreign_key => 'game_subsector_id',:counter_cache => true
我使用 Active Admin 输入游戏、部门或子部门信息。
当我创建游戏时,我有一个非常基本的表单,我只想让第二个选择下拉菜单 (game_subsector) 调整第一个选择 (gamesector) 的选择,这样我就不会全部(很长)game_subsectors 列表,但只有属于我选择的 game_sector 的列表。
在尝试了数十次测试和技术但都失败后,我终于使用了这个似乎与我相关的开发人员建议:http://samuelmullen.com/2011/02/dynamic-dropdowns-with-rails-jquery-and-ajax/。
但还是不行。
这是位于 admin/game.rb 上的 Active Admin 表单
ActiveAdmin.register Game do
menu :parent => "Campaigns", :priority => 1
controller do
with_role :admin_user
def game_subsectors_by_game_sector
if params[:id].present?
@game_subsectors = GameSector.find(params[:id]).game_subsectors
else
@game_subsectors = []
end
respond_to do |format|
format.js
end
end
end
form do |f|
f.inputs "Details" do
f.input :name
f.input :game_sector_id,
:label => "Select industry:",
:as => :select, :collection => GameSector.all(:order => :name),
:input_html => { :rel => "/game_sectors/game_subsectors_by_game_sector" }
f.input :game_subsector_id, :as => :select, :collection => GameSubsector.all(:order => :name)
f.actions
end
我觉得 javascript 甚至可能没有被触发。
我使用的 jquery 位于 app/assets/javascript/admin/active_admin.js(我更改了配置,因此它在加载活动管理页面时加载了这个 javascript)
jQuery.ajaxSetup({
'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript"); }
});
$.fn.subSelectWithAjax = function() {
var that = this;
this.change(function() {
$.post(that.attr('rel'), {id: that.val()}, null, "script");
});
};
$("#game_game_sector_id").subSelectWithAjax(); //it it found in my view???
最后我在 app/views/layout/game_subsectors_by_game_sector.js.erb 中创建了一个视图为this expert adviced:
$("#game_game_subsector_id").html('<%= options_for_select(@game_subsectors.map {|sc| [sc.name, sc.id]}).gsub(/n/, '') %>');
虽然我不确定我把它放在正确的地方......
【问题讨论】:
标签: javascript jquery ruby-on-rails ruby-on-rails-3 activeadmin