You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails+Ajax:如何在Controller中获取CoffeeScript的sub_mod_str值

解决ActiveAdmin中Controller获取CoffeeScript变量值的问题

问题背景

已实现局部视图与CoffeeScript交互,collection_select变更可触发脚本且返回值正确,Controller的new方法能正常调用。需解决:在ActiveAdmin的Command Controller的new方法中获取CoffeeScript里的sub_mod_str值。

解决方案

核心思路:当下拉框选中值变化时,动态更新「Execute」按钮的跳转URL,将选中的sub_mod_str作为URL参数传递,Controller即可通过params获取该值。

1. 修改局部视图,给链接添加唯一ID

给link_to添加ID,方便CoffeeScript定位并修改其URL:

<% @modName = locals[:moduleName] %>
<% @id = locals[:id] %>
<%= form_with url: admin_command_path() do |f| %>
    <%= collection_select(:refcode, :Code, Command.where(FLD: @modName), :Code, :Definition, options ={prompt: true}) %>
    <br /><br />
    <button class="btn_new">
        <%= link_to "Execute", new_admin_command_path(mod: @modName, id: @id), id: "execute_link" %>
    </button>
<% end %>

2. 调整CoffeeScript,动态更新链接参数

监听下拉框变化,获取选中值后更新execute_link的href属性,把sub_mod_str追加到URL参数中:

get_SubModule = ->
    $('#refcode_Code').change (e) ->
      com_value = $('#refcode_Code').val()
      console.log 'COFFEEE IS LIFE', com_value
      # 拆分原链接的基础URL和现有参数
      [baseUrl, existingParams] = $('#execute_link').attr('href').split('?')
      # 用URLSearchParams管理参数,避免手动拼接出错
      urlParams = new URLSearchParams(existingParams || '')
      urlParams.set('sub_mod_str', com_value)
      # 更新链接的href
      $('#execute_link').attr('href', "#{baseUrl}?#{urlParams.toString()}")
      return
    return

3. 在Controller的new方法中获取参数

直接通过params[:sub_mod_str]即可拿到CoffeeScript传递的值:

ActiveAdmin.register Command do
  def new
    # 获取sub_mod_str值
    @sub_mod_str = params[:sub_mod_str]
    # 后续业务逻辑处理
  end
end

内容的提问来源于stack exchange,提问作者Sean Gillespie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 21:18:37