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

