第一次在轨道上处理ruby,我有一个带有以下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的单独表,其中为每个父项输入两次单个注释?
谢谢!
答案 0 :(得分:1)
听起来您正在尝试将Comment实现为连接模型,该模型表示特定用户对Idea的评论。如果是这样,您应该能够如下完成:
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