Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_one with join table

In my app there are Athletes... athletes can have many sports.

Athlete:

has_many :sports, :through => :user_sports
has_one :primary_sport, conditions: ["user_sports.primary = ?", true], class_name: "Sport"
has_many :user_sports

UserSport:

class UserSport < ActiveRecord::Base
  attr_accessible :athlete_id, :sport_id, :primary

  belongs_to :athlete
  belongs_to :sport
end

I am trying to be able to pull back the primary_sport as a Sport object instead of the user_sport object.

like image 579
dennismonsewicz Avatar asked May 08 '13 15:05

dennismonsewicz


1 Answers

Since you pull your sports objects :through user_sports, you should pull your primary_sport object :through user_sports as well.

has_one :primary_sport, :through => :user_sports, conditions: ["user_sports.primary = ?", true], class_name: "Sport"
like image 100
frandroid Avatar answered Oct 12 '22 11:10

frandroid