活跃记录协会

时间:2013-07-26 05:04:31

标签: ruby-on-rails model-associations

我正在为我的高尔夫协会工作。我有几个不同的模型,但当我尝试合并课程时遇到了问题。当高尔夫俱乐部有多个球场或球场名称与高尔夫球俱乐部不同时,球场将代表球场名称(例如:特伦北高尔夫俱乐部有两个球场,Pinnacle和纪念碑)。我不确定如何创建关联

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

我尝试过使用:通过,也没有它。我认为:通过阅读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:找不到关联:模型Round中的回合。

我有点困惑,不知道我要离开的地方。任何帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分: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连接。

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