2009-07-24 6 views
0

J'ai deux tables, "contenus" et "profils" qui peuvent être commentés et notés. J'ai regardé en utilisant des associations polymorphes et ai décidé contre lui. Si j'utilisais des associations polymorphes, la table "ratings" et "comments" auraient tous deux cette fonctionnalité. Est-ce possible avec une implémentation concrète et supertable?Puis-je accomplir cela avec plusieurs supertables en béton?

Et si oui, comment le ferais-je?

Répondre

0

Essayez ceci:

 

class Commentable < ActiveRecord::Base 
    has_many :comments 
    has_one :profile, :content 
end 

class Comment < ActiveRecord::Base 
    belongs_to :commentable 
end 

class Content < ActiveRecord::Base 
    belongs_to :commentable 
end 

class Profile < ActiveRecord::Base 
    belongs_to :commentable 
end 
 

Cela vous permet de (script/console):

 

# every time you create a profile, link it to the 
# commentable row associated to this profile instance 
cid = Commentable.create().id 
p = Profile.create(:name => "Inspector Gadget", 
        :commentable_id => cid) 

# when creating the comment, assign the commentable_id 
# to link it to a Profile comment 
Comment.new do |c| 
    c.body = "go go gadget" 
    c.email = "[email protected]" 
    c.commentable_id = p.commentable_id 
    c.save! 
end 
 

Pour récupérer les commentaires de la base de données à partir d'un profil, utilisez cette astuce:

 

# Profile.rb 

# instead of doing a has many through, 
# we can just use instance method with custom join. 
def comments 
    find(self.id, :joins => "JOIN commentables cm ON (profiles.id = cm.id) 
    LEFT OUTER JOIN comments c ON (cm.id = c.commentable_id)") 
end 
 

Code non testé!

voir ici pour plus de détails et explaination, Why can you not have a foreign key in a polymorphic association?

1

Vous mélangeons des colonnes sur la jointure. Il devrait être ceci:

 

    find(self.id, :joins => "JOIN commentables cm ON (profiles.commentable_id = cm.id) 
    LEFT OUTER JOIN comments c ON (cm.id = c.commentable_id)") 
 
0

-moi si je me trompe, mais ne pourrais pas vous faire juste cela dans Profiles.rb

 

def comments 
    Comments.find(:all, :conditions => ["commentable_id = ?", self.commentable_id]) 
end 
 
Questions connexes