我有以下型号
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
这些是通过players_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中连接表中存储的值?
由于
答案 0 :(得分:1)
由于players_to_teams是一个连接表而你还没有运行它,你得到一个关系。
首先,您需要为集合调用all或首先调用单个PlayersToTeam对象。
另外,我非常肯定它会因为大写(因为Ruby中的常量有大写字符)而会阻塞一个名为BT的方法。