2013-10-07 54 views
27

这里是我的控制器协会命名未发现可能拼错的问题轨协会

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

回答

59

这是典型的错字错误:

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

类似的问题:

+1

YAE其工作。 – overflow

+0

好吧,现在我需要另一个澄清。我在两桌都有'created_at'。我需要两个日期(即)'注册日期'和'发布日期'我怎样才能得到它。 – overflow

+0

这是另一个与这个不相关的问题,如果你想在Stackoverflow上创建另一个问题。 (但通常使用'post.created_at'来获取Post实例的created_at值) – MrYoshiji