Ruby-on-rails 在 Rails 协会中找不到命名的关联可能是拼写错误的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19231629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:50:04 来源:igfitidea点击:
association named not found perhaps misspelled issue in rails association
提问by overflow
Here is my controller
这是我的控制器
@post = Post.joins(:customers).select("customers.*,posts.*").find params[:id]
My post model
我的帖子模型
belongs_to :customer
My customer model
我的客户模型
has_many :posts
And i am getting error as
我收到错误
Association named 'customers' was not found on Post; perhaps you misspelled it?
This is my controller output:
这是我的控制器输出:
Processing by PostsController#show as */*
Parameters: {"id"=>"6"}
Post Load (0.5ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = 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'
回答by MrYoshiji
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:
一些需要了解的内容:
- In the
joins/includesmethod, always use the exact same name as the relation - In the
whereclauses, 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)
- 在
joins/includes方法中,始终使用与关系完全相同的名称 - 在
where子句中,始终使用关系的复数名称(实际上是表的名称,默认情况下是复数形式的模型名称,但也可以手动设置)
Examples:
例子:
# 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:
类似问题:

