简体   繁体   中英

Problems modelling a relational database with ActiveRecord in Ruby on Rails

I have 3 models (User, Team and League) and I'd like to establish the following relationship between them:

  • A User can own multiple Teams.
  • A League consists of multiple Teams and it's owned by a User.
  • A Team belongs to a User and to a League at the same time.

I'm new to Ruby on Rails and I can't seem to figure out how to represent these relationships. When I try to test the models I'm getting errors when I instance a Team because I don't know how to .build a Team from a User and a League at the same time. Any help would be much appreciated, thanks in advance.

Models:

class User < ActiveRecord::Base
  has_many :teams
end

class League < ActiveRecord::Base
  belongs_to :user
  has_many :teams
end

class Team  < ActiveRecord::Base
  belongs_to :league
  belongs_to :user
end

Migrations:

create_table(:users) do |t|
  t.string :name
  t.timestamps
end

create_table(:leagues) do |t|
  t.references :user, index: true
  t.string :name
  t.timestamps
end

create_table(:teams) do |t|
  t.references :league, index: true
  t.references :user, index: true
  t.string :name
  t.timestamps
end

I suggest to read in the Rails Guides about associations and migrations .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM