5

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.

1 Answer 1

6

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"
1
  • 2
    Note this answer about the removal of conditions in favor of using -> { where } in Rails 4.0.
    – theblang
    Dec 20, 2019 at 22:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.