首页 > 解决方案 > link_to 嵌套资源路由找不到 ID

问题描述

我的用户名中的 link_to 正在创建一个错误,我不知道为什么。

错误:

找不到没有 ID 的 StripeAccount

控制器: 这是一个独立于 StripeAccount 控制器的控制器

def settings
    @user = current_user.id
    @stripe_account = StripeAccount.find(params[:stripe_account_id])
  end

我尝试过“@stripe_account = StripeAccount.find(params[:id])”,但出现同样的错误

看法:

<%= link_to user_stripe_account_path(@user, @stripe_account) %>

我尝试过使用@stripe_account.id 等。

楷模:

stripe_account::

  belongs_to :user, optional: true

user::

  has_one :stripe_account

路线:

  resources :users do
    resources :stripe_accounts
  end

当我尝试加载 /settings 页面时出错:

这是我使用时的 CMD:@stripe_account = StripeAccount.find(params[:stripe_account_id])

app/controllers/dashboard_controller.rb:18:in `settings'
Started GET "/settings" for 127.0.0.1 at 2018-11-17 06:27:04 -0500
Processing by DashboardController#settings as HTML
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 2], ["LIMIT", 1]]
  ↳ app/controllers/dashboard_controller.rb:17
Completed 404 Not Found in 3ms (ActiveRecord: 0.3ms)



ActiveRecord::RecordNotFound (Couldn't find StripeAccount without an ID):

app/controllers/dashboard_controller.rb:18:in `settings'

当我使用 @stripe_account = StripeAccount.find(params[:id])

ActiveRecord::RecordNotFound (Couldn't find StripeAccount without an ID):

app/controllers/dashboard_controller.rb:18:in `settings'
Started GET "/settings" for 127.0.0.1 at 2018-11-17 06:28:21 -0500
Processing by DashboardController#settings as HTML
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 2], ["LIMIT", 1]]
  ↳ app/controllers/dashboard_controller.rb:17
Completed 404 Not Found in 3ms (ActiveRecord: 0.3ms)



ActiveRecord::RecordNotFound (Couldn't find StripeAccount without an ID):

app/controllers/dashboard_controller.rb:18:in `settings'

我做错了什么?

我能想到的唯一可能发生的问题是 rails/ruby 正在从 stripe_account 中找到 API ID,其中包含来自 stripe 的一堆信息......如果是这样,有没有一种方法可以使用来自桌子?

标签: ruby-on-railsruby

解决方案


You should be able to do @stripe_account = current_user.stripe_account if you wan't to set the variable to the current_user's stripe account (you have no id param on the request). And I recommend you to use @user = current_user or @user_id = current_user.id since it's confusing to read a variable named @user that has an integer value.

When you define "StripeAccount belongs_to User", by default (it's the convention) ActiveRecord looks for a user_id column on stripe_accounts table.

I'd recommend you to read this https://guides.rubyonrails.org/association_basics.html. It explains all types of associations and you can configure your associations even if they are not conventional (different class names, no _id column, etc).


推荐阅读