2013-10-07 10 views
27

Ecco il mio controllerassociazione non si chiami trovata problema forse errata in associazione rotaie

@post = Post.joins(:customers).select("customers.*,posts.*").find params[:id] 

Il mio post modello

belongs_to :customer 

Il mio modello cliente

has_many :posts 

e sto ottenendo l'errore come

Association named 'customers' was not found on Post; perhaps you misspelled it? 

Questa è la mia uscita del regolatore:

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' 

risposta

59

Questo è un tipico errore di battitura:

@post = Post.joins(:customers).select("customers.*,posts.*").find params[:id] 
# should be: 
@post = Post.joins(:customer).select("customers.*,posts.*").find params[:id] 
          #^^ no plural 

Perché è stato definito il rapporto come questo (usando singolare):

# Post model 
belongs_to :customer 

Alcune cose da sapere:

  • Nel metodo joins/includes, utilizzare sempre lo stesso nome come la relazione
  • Negli where clausole, utilizzare sempre il nome pluralizzato della relazione (in realtà, il nome della tabella, che di default è il modello nome in plurale, ma possono anche essere impostata manualmente)

Esempi:

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

domande simili:

+1

yae suo funzionamento. – overflow

+0

Ok ora ho bisogno di un altro chiarimento. Ho 'created_at' su entrambi i tavoli. Ho bisogno di entrambe le date (i.e) 'Registration Date' e' Post Date'. Come posso ottenerlo. – overflow

+0

Questa è un'altra domanda non correlata a questa, creare un'altra domanda su Stackoverflow, se lo si desidera. (ma di solito si usa 'post.created_at' per ottenere il valore created_at di un'istanza Post) – MrYoshiji