Search code examples
ruby-on-railsscaffolding

steps for creating complex relations between tables


Here (http://allaboutruby.wordpress.com/2009/08/08/5-minute-project-in-rails/) we can see how to create 1-m relation between tables, but what steps should I do to create for example the next kind of the relations between tables:

http://docs.oracle.com/cd/E14373_01/appdev.32/e13363/issue_track_obj.htm

To simplify, just how to create the relation where user can have several created by him bugs and can be assigned to the several bugs created by other users.

Thanks.


Solution

  • First, you need two columns on bugs table, creator_id and assignee_id. Then you just create following relationships:

    class User < ActiveRecord::Base
      has_many :created_bugs, :class_name => 'Bug', :foreign_key => :creator_id
      has_many :assigned_bugs, :class_name => 'Bug', :foreign_key => :assignee_id
    end
    
    class Bug < ActiveRecord::Base
      belongs_to :creator, :class_name => 'User'
      belongs_to :assignee, :class_name => 'User'
    end