【问题标题】:Rails generate options with classes based on parent for jQuery conditional hidingRails 使用基于父级的类生成选项,用于 jQuery 条件隐藏
【发布时间】:2015-12-08 08:49:02
【问题描述】:

我有几个带有选择框的表单,我想根据之前选择的选项有条件地隐藏选项。例如:

在注册页面上,我有 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 来实现这一点。

有什么想法吗?

谢谢

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    你可以这样做

    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 的名称

    【讨论】:

    • 我会试试这个。我认为这应该在代理控制器而不是分支机构控制器中,对吧?
    • 我这样做并更改了路由并在您的路由器中收到此错误ArgumentError at /users/sign_up You should not use the match` 方法,但未指定 HTTP 方法。等等等等`我将它从匹配更改为获取并清除了错误。我现在收到NameError at /users/sign_up undefined local variable or method f'。我怀疑我需要将 f 变量传递给部分分支以使其工作,但我无法正确使用语法
    • 感谢 Rajarshi 的帮助。我现在收到undefined local variable or method branches'` 错误在部分分支中。控制器中的@branches 是否由于某种原因没有被拾取?
    • 嗨,克雷格,看看我的更新帖子:locals => {:f => f, :branches => @branches}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多