在Ruby on Rails上为关联建立数据库



第一次使用ruby on rails,我有以下3个模型的应用程序:

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,其中单个评论为每个父条目输入两次?

谢谢!

这听起来像你正试图实现评论作为一个连接模型,它表明一个特定的用户对一个想法的评论。如果是这样,您应该能够完成如下操作:

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

最新更新