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

Ruby on Rails显示异常:单条Month记录对应多条重复链接

Hey there! No worries at all—we’ve all spent hours stuck on a tricky little bug that seems obvious once you spot it. Let’s fix this duplicate month link issue together.

The Root Cause

The problem comes from how your User and Month association works. You've set up has_many :months, through: :runs in your User model. When a single month has multiple runs tied to the current user, this association returns one month instance per run instead of a single unique month. That's why each new run adds another duplicate link to your index page.

Fix 1: Update the Association (Cleanest Approach)

Modify the months association in your user.rb model to return only unique months using the distinct scope:

class User < ApplicationRecord
  # ... other existing code ...
  has_many :runs
  has_many :months, through: :runs, -> { distinct }
end

This tells Rails to only fetch each unique month once, no matter how many runs are linked to it.

Fix 2: Adjust the Index Controller Action

If you prefer not to modify the model association, you can add the distinct method directly in your months#index action:

def index
  @months = current_user.months.distinct
  @month = Month.new
end

This will filter out duplicate month records before passing them to your view.

How to Verify

You can confirm this was the issue by running this in your Rails console:

current_user = User.find(your_user_id)
puts current_user.months.count # This will match the number of runs, not unique months
puts current_user.months.distinct.count # This should show the correct number of unique months

Either fix will ensure your /months index page only shows one link per unique month, no matter how many runs are associated with it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:35:45