2013-04-04 96 views
1

第一次来Ruby on Rails的工作,我有以下3种型号的应用程序:设立了关于Ruby协会数据库on Rails的

class User < ActiveRecord::Base 
    attr_accessible :username, :name, :email, :password 
    has_many :comments 
    has_many :ideas, :inverse_of => :user 
end 

class Idea < ActiveRecord::Base 
    attr_accessible :title, :description, :rank, :user_id, :status, :privacy, :created_on, :updated_on 
    belongs_to :user, :inverse_of => :ideas 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    attr_accessible :text, :rank, :user_id, :idea_id, :created_on 
    belongs_to :user 
    belongs_to :idea 
end 

我有像创建评论表:

create_table :comments do |t| 
    t.string :comment_id 
    t.string :text 
    t.string :rank 
    t.timestamps 
end 

我想为这些种子。我想了解的是,如何将带有父想法和父用户的单个注释存储在数据库中,因为列一次只能容纳一个父项。我是否应该创建一个包含comment_id,user_id和idea_type的单独表格,其中为每个父代输入两次单个评论?

谢谢!

+0

你能描述你想要多态的关系吗?您是否试图在意见和用户上支持意见,或仅在用户上提供意见?有没有可能的子类的用户? – 2013-04-04 01:28:04

+0

我想要支持用户和意见的评论。我想评论是多态的。我不认为有子类 – BooBailey 2013-04-04 01:32:55

+1

你确定多态性实际上是你在找什么吗?如果您想让意见留在想法或用户身上,那么您会使用多态性,也就是说,它可能有父级用户或想法,但只有其中一个。这就是你想要的,或者你真的想要一个属于一个用户(谁离开它)的评论,以及一个想法(被评论的想法)。如果是这样的话,那么你不需要多态关系,只需要两个'has_many' /'belongs_to'关系。 – 2013-04-04 01:34:58

回答

1

这听起来像你正在试图实现评论作为一个联接模型,它表明一个特定的用户对意见的评论。如果是这样,你应该能够做到如下:

class User < ActiveRecord::Base 
    attr_accessible :username, :name, :email, :password 
    has_many :comments 
    has_many :commented_ideas, :class_name => 'Idea', :through => :comments, :source => :comment 
end 

class Idea < ActiveRecord::Base 
    attr_accessible :title, :description, :rank, :user_id, :status, :privacy, :created_on, :updated_on 
    belongs_to :user # the user who created the Idea 
    has_many :comments 
    has_many :commented_users, :class_name => 'User', :through => :comments, :source => :user 
end 

class Comment < ActiveRecord::Base 
    attr_accessible :text, :rank, :user_id, :idea_id, :created_on 
    belongs_to :user 
    belongs_to :idea 
end 

create_table :comments do |t| 
    t.string :text 
    t.string :rank 
    t.integer :user_id 
    t.integer :idea_id 
    t.timestamps 
end 
+0

谢谢斯图尔特。我有一个关于扩展这个问题。作为在评论用户的基础上创建想法的用户,是否可以在Idea模型中添加belongs_to:user? – BooBailey 2013-04-04 01:47:22

+1

绝对是,更新了我的答案。 – 2013-04-04 01:49:07

+0

谢谢!那么,从理论上讲,我可以继续扩大协会,以描述任何情况? – BooBailey 2013-04-04 01:51:33