Rails has_one与连接表

时间:2013-05-08 15:54:27

标签: ruby-on-rails-3 has-one

在我的应用程序中有Athletes ...运动员可以进行多项运动。

运动员:

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

我正在尝试将primary_sport作为Sport对象而不是user_sport对象拉回来。

1 个答案:

答案 0 :(得分:5)

由于你拉动运动物体:通过user_sports,你应该拉你的primary_sport对象:通过user_sports。

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