2

我有以下型号

class Player < ActiveRecord::Base
  has_many :players_to_teams
  has_many :teams, through: :players_to_teams
end

class Team < ActiveRecord::Base
  has_many :players_to_teams
  has_many :players, through: :players_to_teams
  belongs_to :account
end

这些通过 player_to_teams 表加入:

class PlayersToTeam < ActiveRecord::Base
  belongs_to :player
  belongs_to :team
end

players_to_teams有一个名为 的列BT。我在访问此专栏时遇到了困难。

这失败了:

player = Player.find(13)
player.players_to_teams.BT

出现此错误:

NoMethodError:   undefined method `BT' for #<ActiveRecord::Relation:0x007fd52f170c58>
PlayersToTeam Load (332.2ms)    from /Users/Tyler/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/relation/delegation.rb:45:in `method_missing'
  SELECT `players_to_teams`.* FROM `players_to_teams` WHERE `players_to_teams`.`player_id` = 13
    from /Users/Tyler/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/associations/collection_proxy.rb:101:in `method_missing'
    from (irb):4
    from /Users/Tyler/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.1/lib/rails/commands/console.rb:47:in `start'
    from /Users/Tyler/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.1/lib/rails/commands/console.rb:8:in `start'
    from /Users/Tyler/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.1/lib/rails/commands.rb:41:in `<top (required)>'
    from /Users/Tyler/Development/Rails/csbb/script/rails:6:in `require'
    from /Users/Tyler/Development/Rails/csbb/script/rails:6:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'

但是,这确实有效:

player.players_to_teams.select("BT")

select有没有办法在不使用该选项的情况下访问存储在 Rails 3.2.1 中的连接表中的值?

谢谢

4

1 回答 1

1

由于players_to_teams 是一个连接表并且您没有在其上运行所有内容,因此您得到了一个关系。

首先,您需要为集合调用 all 或首先为单个 PlayersToTeam 对象调用。

此外,我很确定它会因为大写(Ruby 中的常量具有大写字符)而被称为 BT 的方法阻塞。

于 2012-04-04T23:56:18.103 回答