1

第一次在 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 的单独表,其中每个父级的单个评论输入两次?

谢谢!

4

1 回答 1

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
于 2013-04-04T01:41:53.237 回答