在 Rails 协会中找不到命名的关联可能是拼写错误的问题 [英] association named not found perhaps misspelled issue in rails association
本文介绍了在 Rails 协会中找不到命名的关联可能是拼写错误的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的控制器
@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'
推荐答案
这是一个典型的拼写错误:
This is a typical typo error:
@post = Post.joins(:customers).select("customers.*,posts.*").find params[:id]
# should be:
@post = Post.joins(:customer).select("customers.*,posts.*").find params[:id]
#^^ no plural
因为你定义了这样的关系(使用单数):
Because you defined the relation like this (using singular):
# Post model
belongs_to :customer
<小时>
一些需要了解的内容:
Some stuff to know:
- 在
joins
/includes
方法中,始终使用与关系完全相同的名称 - 在
where
子句中,总是使用关系的复数名称(实际上是表的名称,默认是复数形式的模型名称,但也可以手动设置)
- In the
joins
/includes
method, always use the exact same name as the relation - In the
where
clauses, always use the pluralized name of the relation (actually, the table's name, which is by default the model name in plural but can also be manually set)
示例:
# 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' })
#^^ ^
<小时>
类似问题:
- 如何根据属于第一个模型的另一个模型的属性查询模型?
- Rails 活动记录查询与存在"的关联一个>
- Rails 3, has_one/has_many withlambda 条件
- Rails 4 范围来查找父母没有孩子
这篇关于在 Rails 协会中找不到命名的关联可能是拼写错误的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文