首页 > 解决方案 > Ruby on Rails:“显示”帐户路径

问题描述

目前我有两个模型,AccountUser. 账户有很多用户,用户属于账户。我想显示帐户页面但不断No route matches {:action=>"show", :controller=>"accounts"}, missing required keys: [:id]出错。

Accounts控制器

def show
   @account = Account.find_by(params[:id])
end

账户页面链接

<%= link_to "Account Settings", account_path %>

路线

resources :accounts, only: [:new, :create, :show, :edit, :update]

标签: ruby-on-railscontrollerroutes

解决方案


这里的问题:

<%= link_to "Account Settings", account_path %>

Rails 说“缺少必需的键:[:id]”,这意味着你必须发送 id 来显示方法

<%= link_to "Account Settings", account_path(123) %>

当有人点击您的链接后,控制器将在此处获取此 ID:

@account = Account.find_by(params[:id])

将在数据库中找到您的记录,并将您重定向到 :show 页面


推荐阅读