45

这是我的控制器

@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'
4

1 回答 1

114

这是一个典型的拼写错误:

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

类似的问题:

于 2013-10-07T18:09:31.077 回答