2016-12-19 3 views
0

私はRuby on Railsに戻ろうとしていますが、簡単な質問があります。私のアプリケーションは、各トーナメントが1ラウンド以上のゴルフを持つことができるゴルフトーナメントを持つことに基づいています。各ゴルフラウンドは1コースで行われます。アソシエーションのヘルプnewby

私は、次の関連付けを作成しました:

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 

を行うことができるはずと思いましたコースに関連する2つのトーナメントがあるかのように、[0] .tournamentsは重複データを返すようです私は2つのラウンドを持っているからです。

=> #<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

あなたのラウンドは、そのトーナメントhas_one :courseを指定して、移行

に一致するように belongs_toする必要があります
関連する問題