user2128197
user2128197

Reputation: 1

Creating a database relationship that allows for multiple assignments of the same id

I'm really new to RoR so I apologize if I'm not thinking about this right. I have a Report where I need to be able to assign multiple users to that report. A user can be assigned to more than one report and a report can have multiple users. How do I create the database relationship where this would be allowed. I understand how to assign one user to one report but not many users to a single report.

Upvotes: 0

Views: 115

Answers (2)

Jonathan Katon
Jonathan Katon

Reputation: 746

I highly recommend you familiarize yourself with the Ruby on Rails guides. They will prove to be an invaluable asset!! For this task the site would be RailsGuides Active Record Associations.

As far as the code goes you want to create three database tables: reports, reports_users, and users, with reports_users being a join table.

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string      :name,        :null => false      
      t.timestamps
    end
  end
end


class CreateReports < ActiveRecord::Migration
  def change
    create_table :reports do |t|
      t.string      :name,        :null => false      
      t.timestamps
    end
  end
end


class ReportsUsers < ActiveRecord::Migration
  def change
    create_table :reports_users, :id => false do |t|
      t.references    :user,            :null => false                            
      t.references    :report,          :null => false                            
    end
  end
end

Once you run this migration you need to set up the active record associations in your models.

class User < ActiveRecord::Base
  has_and_belongs_to_many :reports
end

class Report < ActiveRecord::Base
  has_and_belongs_to_many :user
end

This will set up the database and the many-to-many models connections. This will get you started. Now you have to go create some views

Upvotes: 0

Richard Brown
Richard Brown

Reputation: 11436

I'd use a joining class to make this happen:

class Report

  has_many :assignments 
  has_many :users :through => :assignments

end

class User

  has_many :assignments
  has_many :reports, :through => :assignments

end

class Assignment

  belongs_to :report
  belongs_to :user

end

The class Assignment has two fields: report_id and user_id to create the relationship.

Read the Ruby on Rails Guide to Active Record Associations: http://guides.rubyonrails.org/association_basics.html

Upvotes: 2

Related Questions