Ruby on rails 活动记录协会
我正在为我的高尔夫协会开发一个网站。我有一些不同的模式,但在尝试合并课程时遇到了问题。当高尔夫俱乐部有多个球场或球场名称与高尔夫俱乐部不同时,球场将代表球场名称(例如:Troon North高尔夫俱乐部有两个球场,Pinnacle和Monument)。我不知道如何创建关联Ruby on rails 活动记录协会,ruby-on-rails,model-associations,Ruby On Rails,Model Associations,我正在为我的高尔夫协会开发一个网站。我有一些不同的模式,但在尝试合并课程时遇到了问题。当高尔夫俱乐部有多个球场或球场名称与高尔夫俱乐部不同时,球场将代表球场名称(例如:Troon North高尔夫俱乐部有两个球场,Pinnacle和Monument)。我不知道如何创建关联 class Tournament < ActiveRecord::Base has_many :rounds, dependent: :destroy has_many :clubs, through:
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
当我尝试执行@round.courses时,我收到以下消息-ActiveRecord::HasManyThroughAssociationNotFoundError:找不到关联:模型轮中的轮
我有点困惑,不知道该怎么办。任何帮助都将不胜感激。谢谢 所属关联应始终为单数。另外,您还没有在迁移过程中指定round_id 在锦标赛模型中,您可以通过“锦标赛.课程”直接访问锦标赛的课程。您不需要使用“through”访问has\u many关系。 乙二醇 “through”关键字实现内部sql联接
在轮次模型中,您无法访问“课程”,因为您通过尚未声明的“轮次”访问它。请理解关系是如何定义的,以及它们在Rails中是如何实际工作的。谢谢您的单数输入。也许我的设计有缺陷,但我没有在球场上指定一个轮滑id,因为球场实际上是俱乐部设置的一部分。我们每年在Troon North的Pinnacle球场举办一次锦标赛。我是否应该创建另一个模型,将它们像圆桌一样连接在一起?
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
@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.