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

Rails如何利用JQuery触发下拉框变更事件时在表单上方展示最新记录

Rails 6.1 下拉框联动查询训练项目最新记录实现方案

1. 新增接口路由

在config/routes.rb中添加AJAX请求对应的路由,指向对应控制器的查询动作:

# config/routes.rb
Rails.application.routes.draw do
  # 保留原有其他路由
  get 'fitness/weights/get_latest_record', to: 'fitness/weights#get_latest_record'
end

2. 编写控制器查询逻辑

在app/controllers/fitness/weights_controller.rb中新增查询动作,接收前端传递的训练项目参数、查询最新记录并返回:

# app/controllers/fitness/weights_controller.rb
class Fitness::WeightsController < ApplicationController
  # 保留原有new、create等动作
  def get_latest_record
    exercise = params[:exercise]
    # 可根据实际业务补充用户权限过滤,例如增加.where(user_id: current_user.id)
    latest_record = Fitness::Weight.where(exercise: exercise).order(created_at: :desc).first
    # 返回内容可根据自身模型字段调整,比如加入组数、备注等信息
    render json: {
      record_text: latest_record ? "#{latest_record.weight}kg × #{latest_record.reps}次 (#{latest_record.created_at.strftime("%Y-%m-%d")})" : "该项目暂无过往记录"
    }
  end
end

3. 调整视图代码

首先在表单顶部新增用于展示历史记录的容器:

<!-- 放在_form表单最上方 -->
<div id="latest-exercise-record" style="margin: 1rem 0; padding: 0.8rem; border-radius: 4px; background: #f5f5f5;"></div>

然后添加下拉框的change事件监听代码,可根据项目是否引入jQuery二选一:

方案A:jQuery版本(适配你之前的使用习惯)

$('#fitness_weight_exercise').on('change', function() {
  const selectedExercise = $(this).val();
  const $recordContainer = $('#latest-exercise-record');
  if (!selectedExercise) {
    $recordContainer.text('请先选择训练项目');
    return;
  }
  $.ajax({
    url: '/fitness/weights/get_latest_record',
    method: 'GET',
    data: { exercise: selectedExercise },
    success: function(res) {
      $recordContainer.text(res.record_text);
    },
    error: function() {
      $recordContainer.text('获取记录失败,请刷新后重试');
    }
  })
})

方案B:原生JS版本(无需依赖jQuery)

document.querySelector('#fitness_weight_exercise').addEventListener('change', function() {
  const selectedExercise = this.value;
  const recordContainer = document.querySelector('#latest-exercise-record');
  if (!selectedExercise) {
    recordContainer.textContent = '请先选择训练项目';
    return;
  }
  fetch(`/fitness/weights/get_latest_record?exercise=${encodeURIComponent(selectedExercise)}`)
    .then(res => res.json())
    .then(data => {
      recordContainer.textContent = data.record_text;
    })
    .catch(err => {
      recordContainer.textContent = '获取记录失败,请刷新后重试';
    })
})

注意事项

  • 如果你的训练项目是通过id关联的独立模型,可将传递参数改为exercise_id,查询逻辑对应调整即可,整体流程不变
  • 若模型没有放在fitness命名空间下,控制器查询时去掉Fitness::前缀即可

内容的提问来源于stack exchange,提问作者John Cowan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:24:07