这是我的控制器
@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
一些需要了解的事情:
- In the
joins
/includes
方法,始终使用与关系完全相同的名称
- In the
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' })
#^^ ^
类似问题:
- 如何根据属于第一个模型的另一个模型的属性查询模型? https://stackoverflow.com/questions/23633301/how-to-query-a-model-based-on-attribute-of-another-model-which-belongs-to-the-fi/23633352#23633352
- Rails 活动记录查询与“存在”的关联 https://stackoverflow.com/questions/18234602/rails-active-record-querying-association-with-exists/18234998#18234998
- Rails 3,具有 lambda 条件的 has_one / has_many https://stackoverflow.com/questions/13515225/rails-3-has-one-has-many-with-lambda-condition/13516285#13516285
- Rails 4 可以找到没有孩子的父母 https://stackoverflow.com/questions/18082096/rails-4-scope-to-find-parents-with-no-children/18082147#18082147
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)