link_to嵌套资源路由找不到ID

问题描述 投票:1回答:2

我的用户名中的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,它包含来自条带的一堆信息......如果是这样,有没有办法可以使用来自表?

ruby-on-rails ruby
2个回答
1
投票

如果你不想将变量设置为current_user的条带帐户(你的请求中没有id参数),你应该能够做@stripe_account = current_user.stripe_account。我建议你使用@user = current_user@user_id = current_user.id,因为它很难读取一个名为@user且具有整数值的变量。

当您定义“StripeAccount belongs_to User”时,默认情况下(这是约定)ActiveRecord在user_id表上查找stripe_accounts列。

我建议你阅读这个https://guides.rubyonrails.org/association_basics.html。它解释了所有类型的关联,您可以配置您的关联,即使它们不是传统的(不同的类名,没有_id列等)。


0
投票

经过多次尝试,我有一种方法可以工作。我不确定这是多么有效,我会探索更多的选择。

最终我的工作方式如下:

@stripe_account = StripeAccount.find_by(params[:id])

关键是使用“.find_by”而不是“.find”。这允许link_to操作并转到正确的位置。

© www.soinside.com 2019 - 2024. All rights reserved.