Rails 5中Show动作关联记录显示异常求助
Hey there, let's break down what's going wrong here and how to fix it.
The Root Problem
Your show method in accounts_controller.rb has a line that's overriding the correct associated Plan for your Account:
@account.plan = Plan.find_by(params[:plan_id])
Here's why this causes the wrong Plan to show up:
- When you use
belongs_to :planin your Account model, Rails automatically handles loading the associated Plan via theplan_idcolumn on theaccountstable. You don't need to manually fetch it again. - The
Plan.find_by(params[:plan_id])call uses incorrect syntax. Ifparams[:plan_id]isn't present (which it won't be in a standard Account show request), this will effectively look for a Plan with no matching conditions—returning the first Plan in your database instead of the one actually linked to the Account.
The Fix
- Remove the problematic line from your
showmethod. Your corrected controller code should look like this:
def show @account = Account.find(params[:id]) end
Double-check your model associations (it looks like you already have this set up, but verification never hurts):
- In
account.rb:belongs_to :plan - In
plan.rb:has_many :accounts - Ensure your
accountsdatabase table has aplan_idinteger column (this should exist if you ran the migration for the association).
- In
Display the Plan name in your view (e.g.,
app/views/accounts/show.html.erb) using the auto-loaded association:
<%= @account.plan.name %>
Why This Works
Now, when you fetch @account = Account.find(params[:id]), Rails will lazy-load the associated Plan using the Account's plan_id value. This ensures you always get the exact Plan linked to that specific Account, not a random or incorrect one.
内容的提问来源于stack exchange,提问作者Shawn Wilson

