Активные записи ассоциаций
Я работаю над сайтом для моей ассоциации гольфа. У меня есть несколько разных моделей, но я столкнулся с проблемой, когда попытался включить курсы. Поле будет представлять название курса, если в гольф-клубе имеется более одного поля, или название курса отличается от названия гольф-клуба (например, в гольф-клубе 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
Я пытался использовать: через, а также без него. Я думал, что: через можно использовать после прочтения 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 ответ
Ассоциация own_to всегда должна быть единственной. Кроме того, вы не указали round_id в миграции для курса.
В модели "Турнир" вы можете напрямую получить доступ к курсам турнира с помощью "tour.courses". Вам не нужно получать доступ к отношению has_many, используя 'through'. например
@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.