2013-10-07 51 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