0

ユーザーと勤務表の間に多対多の関連付けを設定しました。特定の勤務表の作成者も保存しようとしています。

クラス ユーザー

  has_many :rotazations
  has_many :rotas, :through => :rotazations

クラス・ロタ

  has_many :rotazations
  has_many :users, :through => :rotazations, :order => 'name ASC'

クラスローテーション

  belongs_to :user
  belongs_to :rota

  before_create do |rotazation|
    rotazation.creator_id = rotazation.user_id
  end

勤務表が作成されると、勤務表を作成したユーザーのIDを持つようにrotazationテーブルのcreator_idを正常に設定しました。私の質問は、どのようにアクセスするのですか:

rota.creator

私の試み

私は以下を追加しようとしました:

ロタクラス

...
belongs_to :creator, :class_name => "User", :through => :rotazations, :foreign_key => "creator_id"  
...

ユーザークラス

has_many :created_rotas, :class_name=> "Rota", :through => :rotazations, :foreign_key => "creator_id"  

ただし、これは機能しません。rota.creator の作業を達成する方法はありますか? ありがとう!

4

1 に答える 1

1

rotazationsテーブルに新しい行を作成するたびに、 の属性である を にuser_id追加します。creator_idRotazation

ただし、rotazationsテーブルは多対多の関係を解決するためのuser_idとの組み合わせです。rota_id私の考えが正しければ、creator_idは常に と同じになりuser_idます。したがって、実際には冗長データがあります。

| user_id | rota_id |creator_id |
| 1       | 1       | 1         |
| 2       | 1       | 2         |
| 1       | 2       | 1         |
| ...     | ...     | ...       |

誰が新しい属性を作成したかを知るために、テーブルにRota新しい属性を追加できます。rotascreator

user_id新しい勤務表を作成すると、この新しい属性に保存できます。

@rota = Rota.new
@rota.creator = current_user.id
于 2012-07-29T13:21:43.657 に答える