【问题标题】:Rails has_one with join tableRails has_one 与连接表
【发布时间】:2013-05-08 15:54:26
【问题描述】:

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

运动员:

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

用户运动:

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

  belongs_to :athlete
  belongs_to :sport
end

我试图能够将 primary_sport 作为 Sport 对象而不是 user_sport 对象拉回。

【问题讨论】:

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


    【解决方案1】:

    由于您通过 user_sports 拉动您的运动对象,因此您也应该通过 user_sports 拉动您的 primary_sport 对象。

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

    【讨论】:

    • 注意 this answer 关于删除 conditions 以支持在 Rails 4.0 中使用 -&gt; { where }
    猜你喜欢
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多