我是尝试理解ActiveRecord中的关联的新手,它当前正在将#<ActiveRecord::Relation []>
返回到我在Web控制台中运行的查询。
简而言之,我阅读了Rails指南并认为has_and_belongs_to_many
是最佳解决方案。我的终端显示它正在运行查询,但它似乎只是返回一个空数组,输出在下面。
Processing by ScheduleController#show as HTML
Parameters: {"id"=>"1"}
Schedule Load (0.2ms) SELECT "schedules".* FROM "schedules" WHERE "schedules"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Player Load (0.3ms) SELECT "players".* FROM "players" WHERE "players"."team" = ? [["team", "@schedule.home"]]
我有一个Schedule
和一个Players
模型,其目的是根据主队和客队名称返回一个球员名单。
模型/ player.rb
class Player < ApplicationRecord
has_and_belongs_to_many :schedules
end
模型/ schedule.rb
class Schedule < ApplicationRecord
has_and_belongs_to_many :players
end
分贝/迁移/(数字)_create_schedules.rb
class CreateSchedules < ActiveRecord::Migration[5.0]
def change
create_table :schedules do |t|
t.string :leagueGame
t.string :home
t.string :homeAbr
t.string :away
t.string :awayAbr
t.string :venue
t.string :prettyDate
t.string :homeLogo
t.string :homeLogoLarge
t.string :awayLogo
t.string :awayLogoLarge
t.date :date
t.timestamps
end
create_table :player_schedule do |t|
t.belongs_to :player, index: true
t.belongs_to :schedule, index: true
end
end
end
分贝/迁移/(数字)_create_players.rb
class CreatePlayers < ActiveRecord::Migration[5.0]
def change
create_table :players do |t|
t.string :name
t.string :team
t.string :shoots
t.string :catches
t.string :position
t.string :abr
t.integer :number
t.integer :gp
t.integer :goals
t.integer :assists
t.integer :points
t.integer :pim
t.integer :plusMinus
t.decimal :gaa
t.integer :svs
t.timestamps
end
end
end
控制器/ schedule_controller.rb
# For brevity
def show
@schedule = Schedule.find(params[:id])
@home_lineup = Player.where(team: '@schedule.home')
end
@home_lineup
是返回空数组的调用。我可以调用@schedule.home
并显示正确的团队名称,但是我可以像在表查找中一样调用它吗?
答案 0 :(得分:1)
替换
@home_lineup = Player.where(team: '@schedule.home')
与
@home_lineup = Player.where(team: @schedule.home)
根据您的代码,您正在搜索名称为&#39; @ schedule.home&#39;而不是实际的团队名称。