45

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" = $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'
Prabhakaran
  • 3,900
  • 15
  • 46
  • 113

1 Answers1

120

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/includes method, always use the exact same name as the relation
  • In the where clauses, 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)

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:

Community
  • 1
  • 1
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
  • Ok now i need another clarification. I have `created_at` at both table. I need both dates(i.e) `Registration Date` and `Post Date` How can i get it. – Prabhakaran Oct 07 '13 at 18:16
  • This is another question that is not related to this one, create another question on Stackoverflow if you want. (but usually you use `post.created_at` to get the created_at value of a Post instance) – MrYoshiji Oct 07 '13 at 18:22
  • Why couldn't Rails be non-pluralized in all cases by default? No more pluralization errors.. – Magne Dec 05 '13 at 14:50