gpt4 book ai didi

ruby-on-rails - Rails 协会中未找到名为关联的可能拼写错误的问题

转载 作者:行者123 更新时间:2023-12-03 07:30:06 25 4
gpt4 key购买 nike

这是我的 Controller

@post = Post.joins(:customers).select("customers.*,posts.*").find params[:id]

我的帖子模型

belongs_to :customer

我的客户模型

has_many :posts

我收到错误为

Association named 'customers' was not found on Post; perhaps you misspelled it?

这是我的 Controller 输出:

Processing by PostsController#show as */*
Parameters: {"id"=>"6"}
Post Load (0.5ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMIT 1 [["id", "6"]]
Completed 500 Internal Server Error in 113ms

ActiveRecord::ConfigurationError (Association named 'customers' was not found on Post; perhaps you misspelled it?):
app/controllers/posts_controller.rb:16:in `show'

最佳答案

这是一个典型的拼写错误:

@post = Post.joins(:customers).select("customers.*,posts.*").find params[:id]
# should be:
@post = Post.joins(:customer).select("customers.*,posts.*").find params[:id]
#^^ no plural

因为您像这样定义了关系(使用单数):

# Post model
belongs_to :customer
<小时/>

一些需要知道的事情:

  • joins/includes 方法中,始终使用与关系完全相同的名称
  • where 子句中,始终使用关系的复数名称(实际上是表的名称,默认情况下是复数模型名称,但也可以手动设置)

示例:

# Consider these relations:
User has_many :posts
Post belongs_to :user

# Usage of joins/includes & where:
User.includes(:posts).where(posts: { name: 'BlogPost #1' })
#^ ^
Post.joins(:user).where(users: { name: 'Little Boby Table' })
#^^ ^
<小时/>

类似问题:

关于ruby-on-rails - Rails 协会中未找到名为关联的可能拼写错误的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19231629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com