名为not found的关联可能是rails association中的拼写错误的问题

时间:2013-10-07 18:07:23

标签: ruby-on-rails ruby-on-rails-3

这是我的控制器

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

1 个答案:

答案 0 :(得分:80)

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

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

类似问题: