16

मेरे पास रेल में कई रिश्ते हैं। सभी डेटाबेस टेबल तदनुसार और उचित रूप से नामित हैं। सभी मॉडल फाइल बहुवचन हैं और अलग शब्दों के लिए अंडरस्कोर का उपयोग करें। सभी नामकरण सम्मेलन के बाद रूबी और रेल मानकों का पालन किया जाता है। मैं अपने मॉडल में इस तरह से कई का उपयोग कर रहा हूं:ActiveRecord :: HasManyThroughAssociationNotFoundError UserController # स्वागत

has_many :users, :through => :users_posts #Post model 
has_many :posts, :through => :users_posts #User model 
belongs_to :users #UsersSource model 
belongs_to :posts #UsersSource model 

यह त्रुटि और क्या हो सकती है?

ActiveRecord::HasManyThroughAssociationNotFoundError in UsersController#welcome Could not find the association :users_posts in model Post

+0

वास्तव में एक ही समस्या यहाँ हल: http://stackoverflow.com/questions/944126/rails-has

आप सिर्फ एक सरल तालिका में शामिल होने चाहते हैं, यह पुरानी HABTM सिंटैक्स का उपयोग करना आसान है -कई-थ्रू-समस्या – 18bytes

उत्तर

36

आप जब has_many :through का उपयोग कर एक अलग संगठन के रूप में मॉडल में शामिल होने के निर्धारित करने होंगे: जब आप डेटा है कि मॉडल में ही शामिल हो, या यदि से संबंधित है रखने की जरूरत है

class Post < ActiveRecord::Base 
    has_many :user_posts 
    has_many :users, :through => :user_posts 
end 

class User < ActiveRecord::Base 
    has_many :user_posts 
    has_many :posts, :through => :user_posts 
end 

class UserPost < ActiveRecord::Base 
    belongs_to :user # foreign_key is user_id 
    belongs_to :post # foreign_key is post_id 
end 

यह सबसे अच्छा काम करता आप अन्य दो मॉडलों से अलग होने पर सत्यापन करना चाहते हैं।

class User < ActiveRecord::Base 
    has_and_belongs_to_many :posts 
end 

class Post < ActiveRecord::Base 
    has_and_belongs_to_many :users 
end