Search code examples
ruby-on-railsmigrationseeding

setting up databases for associations on Ruby on Rails


First time working on ruby on rails and I have an app with the following 3 models:

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

I have a table for Comments created like:

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

I am trying to seed for these. What I'm trying to understand is how a single comment with a parent idea and a parent user is stored in the database, since the columns can only hold one parent at a time. Should I create a separate table that holds comment_id, user_id and idea_type, where a single comment gets entered in twice for each parent?

Thanks!


Solution

  • It sounds like you are trying to implement Comment as a join model which indicates that a particular User's comment on an Idea. If so, you should be able to accomplish that as follows:

    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