2009-06-22 18 views
11

मैं निम्नलिखित बनाने के लिए कोशिश कर रहा हूँ की दो से जुड़ा हुआ बनाने के लिए कैसे:रेल - एक मॉडल एक और मॉडल

User model (this is fine) 

id 

Link model (associated with two Users) 

id 
user_id1 
user_id2 

यह एक उदाहरण है, जिसमें मैं लिंक मॉडल पर has_and_belongs_to_many संघ प्रकार का उपयोग करना होगा है ? मुझे यह कैसे करना चाहिए?

अंत में, मैं एक उपयोगकर्ता वस्तु है और कॉल @ user.links कि उपयोगकर्ता को शामिल सभी लिंक प्राप्त करने के लिए करने में सक्षम होना चाहते हैं ...

मैं बस का सबसे अच्छा तरीका यह करने के लिए क्या यकीन नहीं है रेल में है।

उत्तर

15

आप बहुत संभावना दो मॉडल इस प्रकार के रूप में संरचित करना चाहते हैं जाएगा:

class User < ActiveRecord::Base 
    has_many :friendships 
    has_many :friends, :through => :friendships #... 
end 

class Friendship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id' 
end 

# ...and hence something like this in your view 
<% for friendship in @user.friendships %> 
    <%= friendship.status %> 
    <%= friendship.friend.firstname %> 
<% end %> 

(। यह पैटर्न RailsForum पर this discussion दौरान लगभग दो साल पहले Ryan Bates द्वारा किए गए एक पोस्ट से है)


बस एक नोट: यह अब काफी पुराना है। आप आधुनिक रेल संदर्भ में इसे संभालने के लिए अन्य रणनीतियों का मूल्यांकन करने पर विचार करना चाह सकते हैं।

+0

बहुत बढ़िया है, धन्यवाद! – cakeforcerberus

1

आप बना सकते हैं एक में शामिल हों मॉडल है कि दोनों के बीच उन मॉडलों

लिंक के बीच संबंध इतने मूल रूप से

 

class User 

    has_many :links, :through => :relationships 

end 

class Relationship 

    belongs_to :user_id_1, :class=> "User" 
    belongs_to :user_id_2, :class=> "User" 

end 

संबंधित मुद्दे