ove*_*low 38 ruby-on-rails ruby-on-rails-3
这是我的控制器
@post = Post.joins(:customers).select("customers.*,posts.*").find params[:id]
Run Code Online (Sandbox Code Playgroud)
我的帖子模型
belongs_to :customer
Run Code Online (Sandbox Code Playgroud)
我的客户模特
has_many :posts
Run Code Online (Sandbox Code Playgroud)
我得到的错误是
Association named 'customers' was not found on Post; perhaps you misspelled it?
Run Code Online (Sandbox Code Playgroud)
这是我的控制器输出:
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'
Run Code Online (Sandbox Code Playgroud)
MrY*_*iji 91
这是一个典型的拼写错误:
@post = Post.joins(:customers).select("customers.*,posts.*").find params[:id]
# should be:
@post = Post.joins(:customer).select("customers.*,posts.*").find params[:id]
#^^ no plural
Run Code Online (Sandbox Code Playgroud)
因为您定义了这样的关系(使用单数):
# Post model
belongs_to :customer
Run Code Online (Sandbox Code Playgroud)
有些事要知道:
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' })
#^^ ^
Run Code Online (Sandbox Code Playgroud)
类似的问题:
| 归档时间: |
|
| 查看次数: |
23848 次 |
| 最近记录: |