簡體   English   中英

在Ruby on Rails上建立用於關聯的數據庫

[英]setting up databases for associations on Ruby on Rails

第一次使用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,在其中為每個父級輸入兩次單個注釋?

謝謝!

聽起來您正在嘗試將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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM