繁体   English   中英

Rails为基于jQuery的条件隐藏生成基于父类的选项

[英]Rails generate options with classes based on parent for jQuery conditional hiding

我有几种带有选择框的表格,我想根据以前选择的选项有条件地隐藏这些选项。 例如:

在注册页面上,我有2个选择框:代理和分支。 代理商选择使用

<%= f.select(:agency_id, options_from_collection_for_select(Agency.all, :id, :name), prompt: 'Select your Agency') %>

和分支之一:

<%= f.select(:branch_id, options_from_collection_for_select(Branch.all, :id, :name), prompt: 'Select your Branch') %>

楷模:

Branch belongs_to :agency
Agency has_many :branches

我只想根据所选代理商显示分支机构。 我不是jQuery专家,但是我确定是否可以根据其代理机构将类添加到分支选项中,然后可以使用一些基本的javascript来实现这一目标。

有任何想法吗?

谢谢

你可以这样

function getBranches(agency_id) {  
  jQuery.ajax({
    url: "/get_branches",
    type: "GET",
    data: {"agency_id" : agency_id},
    dataType: "html"
    success: function(data) {
      jQuery("#branches").html(data);
    }
  });
 }

现在在控制器中

def get_branches
  @branches = Agency.find(params[:agency_id]).branches
  render :partial => 'branches', :locals => {:f => f, :branches => @branches}
end

现在查看您的视图

<%= f.select :agency_id, options_from_collection_for_select(Agency.all, :id, :name), prompt: 'Select your Agency', :onchange => "getBranches(this.value)" %>
<div id="branches">
  <%= render :partial => 'branches', :locals => {:f => f, :branches => @branches} %>
</div>

局部视图_branches.html.erb

<%=  f.select :branch_id, options_from_collection_for_select(branches, "id", "name"), :prompt => "Select a Branch of the Agency" %>

在路线上

match "/get_branches" => "<controller_name>#get_branches"

controller_name是定义get_branchescontroller的名称

暂无
暂无

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

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