这是我的控制器

@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?

这是我的控制器输出:

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' })
              #^^           ^

Similar questions:

Ruby-on-rails相关问答推荐

确定当前太平洋时区是PST还是PDT

使用ImportMaps将HighLightJS添加到rails 7.1

合成轨道布局

Rails:比枚举更惯用的排序/可比较列表方法?

如何配置我的 Rails 应用程序(使用 Puma)以通过 HTTPS 提供服务?

为什么 Image_tag 产生images/...而不是assets/....?

如何启动 rails 控制台并专门使用测试数据库?

Rails 是否带有未授权异常?

注册表单上是否需要 CSRF 保护?

默认情况下,如何在 Rails 中使 cookie 安全(仅限 https)?

在 Rails 中,如何处理多个选中的复选框,只需拆分 , 或?

添加自定义字段/列以使用 Rails 4 进行设计

RSpec > 有没有办法用一个命令运行所有测试?

如何将字符串转换为类方法?

什么是Ruby 用于 BESIDES 轨道?

快速添加链接[:notice]

ruby/ruby on rails 内存泄漏检测

Ruby 中有与 slice 函数相反的函数吗?

ArgumentError:ApplicationController 的副本已从模块树中删除,但仍处于活动状态

Date.current 和 Date.today 有什么区别?