0

以下の関連付けで2つのモデルを作成しました

class User < ActiveRecord::Base
  has_many :roles, :dependent => :destroy
end

class Role < ActiveRecord::Base
  belongs_to :user
end

class Student < Role
end

class Tutor < Role
end

ただし、新しい子ロールを作成すると、そのロールが属するモデルに関連付けられると思います。

そのような:

Tutor.create(:user_id => user_id)

私は期待します:

#some user @user
@user.roles

家庭教師を含む配列を持つこと。ただし、機能していないようです。私が間違っていることについて何か考えはありますか?

4

1 に答える 1

1

単一テーブル継承の使用を開始すると、このタイプのクエリに関するアクティブ レコードに関する限り、作成した Tutor はロールではありません。

class User < ActiveRecord::Base
  has_many :roles
  has_many :tutors
end

@user = User.first
@user.roles
=> []

@user.tutors
=> [#<Tutor id: 1, user_id: 1, type: "Tutor", created_at: "2012-10-26 18:15:16", updated_at: "2012-10-26 18:15:16">]

ユーザーが持つ可能性のあるすべてのロールのリストを取得する場合:

Role.where(user_id: @user.id).all

[#<Tutor id: 1, user_id: 1, type: "Tutor", created_at: "2012-10-26 18:15:16", updated_at: "2012-10-26 18:15:16">, #<Student id: 2, user_id: 1, type: "Student", created_at: "2012-10-26 18:18:32", updated_at: "2012-10-26 18:18:32">]

于 2012-10-26T18:20:50.183 に答える