1

我正在为我的高尔夫协会创建一个网站。我有几个不同的模型,但是当我尝试合并课程时遇到了问题。当高尔夫俱乐部拥有多个球场或球场名称与高尔夫俱乐部不同时,球场将代表球场名称(例如:Troon North 高尔夫俱乐部有两个球场,Pinnacle 和 Monument)。我不确定如何创建关联

class Tournament < ActiveRecord::Base
    has_many :rounds, dependent: :destroy
    has_many :clubs, through: :rounds, dependent: :destroy
    // do I need this to be able to do @tournament.rounds.first.course.first.name?
    has_many :courses, through: :rounds

class Round < ActiveRecord::Base
    belongs_to :tournament
    belongs_to :club
    // not all rounds will have a course
    has_many :courses, :through => :rounds

class Club < ActiveRecord::Base  
    has_many :rounds, dependent: :destroy
    has_many :tournaments, :through => :rounds, dependent: :destroy
    has_many :club_images, dependent: :destroy
    // not all clubs will have a course
    has_many :courses, dependent: :destroy

class Course < ActiveRecord::Base
    belongs_to :club
    belongs_to :rounds

我试过使用 :through 也没有它。我认为 :through 可以在阅读http://guides.rubyonrails.org/association_basics.html,第 2.4 节后使用。

create_table "clubs", :force => true do |t|
  t.string   "name"
  t.string   "address"
  t.string   "city"
  t.string   "state"
  t.string   "zip"
  t.string   "phone"
  t.string   "website"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "logo_file_name"
  t.string   "logo_content_type"
  t.integer  "logo_file_size"
  t.datetime "logo_updated_at"
end

create_table "courses", :force => true do |t|
  t.integer  "club_id"
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "rounds", :force => true do |t|
  t.integer  "tournament_id"
  t.integer  "club_id"
  t.integer  "course_id"
  t.datetime "start_time"
  t.datetime "checkin_time"
  t.datetime "entry_deadline"
  t.decimal  "member_fee"
  t.decimal  "guest_fee"
  t.boolean  "scoring"
  t.boolean  "lunch_included"
  t.text     "comments"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "tournaments", :force => true do |t|
  t.string   "name"
  t.date     "start_date"
  t.date     "end_date"
  t.text     "comments"
  t.text     "practice_round_comments"
  t.datetime "created_at"
  t.datetime "updated_at"
end

当我尝试执行@round.courses 时,我收到以下消息 - ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :rounds in model Round.

我有点困惑,不知道我在哪里。任何帮助,将不胜感激。谢谢!

4

1 回答 1

0

belongs_to 关联应该始终是单数的。此外,您还没有在课程迁移中指定 round_id。

在锦标赛模式中,您可以通过“tournament.courses”直接访问锦标赛的课程。您不需要使用“通过”来访问 has_many 关系。例如

@tournament.rounds.first.courses.first.name #is wrong way
@tournament.courses.first.name #is the correct way since you have defined a has_many relationship. 

'through' 关键字实现了一个内部 sql 连接。

在回合模型中,您无法访问“课程”,因为您正在“通过”尚未声明的“回合”访问它。请了解关系是如何定义的以及它们在 Rails 中的实际工作方式。

于 2013-07-26T05:18:28.683 回答