协会帮助newby

时间:2016-12-19 21:46:07

标签: ruby-on-rails associations

我正在尝试回到Ruby on Rails,但有一个看似简单的问题。我的申请是基于高尔夫锦标赛,每场比赛可以有一轮或多轮高尔夫。每轮高尔夫球都在一个球场上进行。

我创建了以下关联:

class Course < ApplicationRecord
  has_many :rounds, dependent: :destroy
  has_many :tournaments, :through => :rounds, dependent: :destroy
  has_attached_file :logo
end

class Tournament < ApplicationRecord
  has_many :rounds, dependent: :destroy
  has_many :courses, through: :rounds, dependent: :destroy
end

class Round < ApplicationRecord
  belongs_to :tournament
  has_one :course, dependent: :destroy
end

我可以执行以下操作:

- tournament.rounds
- tournament.rounds[0] or tournament.rounds[1]
- course.tournaments
- course.rounds

我以为我应该能够做到以下

- tournament.courses

此外,课程[0] .tournaments似乎返回重复数据,好像有两个锦标赛与课程相关,因为我有两轮。

=> #<ActiveRecord::Associations::CollectionProxy [#<Tournament id: 1, name: "December", start_date: "2016-12-20", end_date: "2016-12-20", comments: "", practice_round_comments: "", created_at: "2016-12-19 18:57:25", updated_at: "2016-12-19 18:57:25">, #<Tournament id: 1, name: "December", start_date: "2016-12-20", end_date: "2016-12-20", comments: "", practice_round_comments: "", created_at: "2016-12-19 18:57:25", updated_at: "2016-12-19 18:57:25">]

我的迁移看起来像这样:

class CreateRounds < ActiveRecord::Migration[5.0]
  def change
    create_table :rounds do |t|
      t.belongs_to :tournament, index: true
      t.belongs_to :course, index: true
      t.datetime :start_time, :null => false
      t.datetime :checkin_time, :null => false
      t.datetime :entry_deadline, :null => false
      t.decimal :member_fee, :precision => 6, :scale => 2, :default => 65.00
      t.decimal :guest_fee, :precision => 6, :scale => 2, :default => 75.00
      t.boolean :scoring, :default => true
      t.boolean :lunch_included, :default => false
      t.text :comments, :null => true

      t.timestamps
    end
  end
end

class CreateTournaments < ActiveRecord::Migration[5.0]
  def change
    create_table :tournaments do |t|
      t.string :name, :null => false
      t.date :start_date, :null => false
      t.date :end_date, :null => false
      t.text :comments, :null => true
      t.text :practice_round_comments, :null => true

      t.timestamps
    end
  end
end

class CreateCourses < ActiveRecord::Migration[5.0]
  def change
    create_table :courses do |t|
      t.string :name, :limit => 30, :null => false
      t.string :address, :limit => 30, :null => false
      t.string :city, :limit => 30, :null => false
      t.string :state, :limit => 2, :null => false
      t.string :zip, :limit => 9, :null => false
      t.string :phone, :limit => 10, :null => false
      t.string :website, :limit => 100, :null => true
      t.attachment :logo

      t.timestamps
    end
  end
end

1 个答案:

答案 0 :(得分:1)

您的回合指定锦标赛has_one :course并且belongs_to应与您的迁移相匹配