BrantDFaulkner
BrantDFaulkner

Reputation: 33

Ruby Rails ActiveRecord Association, has_one through a belongs_to relationship

Models

class GameResult < ActiveRecord::Base
  has_many :games
end

class Game < ActiveRecord::Base
  belongs_to :game_result
end

Schema

create_table "game_results", force: :cascade do |t|
  t.string   "result"
end

create_table "games", force: :cascade do |t|
  t.integer  "game_result_id"
end

I can currently retrieve the result by calling

@game.game_result.result

By building the correct association, I believe I should be able to call

@game.result

I have tried many configurations of a has_many/one through associations to no avail, such as:

class Game < ActiveRecord::Base
  belongs_to :game_result
  has_one :result, through: :game_result, source: :result
end

I would appreciate any advice on how to go about this. Thanks!

Upvotes: 1

Views: 395

Answers (1)

j-dexx
j-dexx

Reputation: 10406

class Game < ActiveRecord::Base
  belongs_to :game_result  
end

You want to call

@game.game_result.result as @game.result

You can't do that with associations, you'd need to use rails' delegator

class Game < ActiveRecord::Base
  belongs_to :game_result  
  delegate :result, to: :game_result, allow_nil: true
end

You might not need allow_nil on the end, depends on your circumstances.

Essentially this is just a shorthand way of having

class Game < ActiveRecord::Base
  belongs_to :game_result  

  def result
    return nil if game_result.nil?
    game_result.result
  end
end

Upvotes: 2

Related Questions