Tyler DeWitt
Tyler DeWitt

Reputation: 23576

Access Columns of Join Table Rails

I have the following models

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

These are joined via the players_to_teams table:

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

players_to_teams has a column called BT. I am having difficulty in accessing this column.

This fails:

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

with this error:

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>'

But, this DOES work:

player.players_to_teams.select("BT")

Is there a way to access values stored in a join table in Rails 3.2.1 without using the select option?

Thanks

Upvotes: 2

Views: 1579

Answers (1)

Omar Qureshi
Omar Qureshi

Reputation: 9093

Since players_to_teams is a join table and you havent run all on it, you get a Relation.

Firstly you need to call either all for a collection or first for a single PlayersToTeam object.

Also, im pretty sure it would choke on a method called BT because of the uppercasing (constants in Ruby have upper cased characters).

Upvotes: 1

Related Questions