2

Rails 3.2 アプリでは、同じ 2 つのモデル間に 2 つの関連付けを設定する必要があります。

例えば

class User
  has_many :events
  has_many :attendances
  has_many :attended_events, through: :attendances
end

class Event
  belongs_to :event_organizer, class_name: "User"
  has_many :attendances
  has_many :attendees, through: :attendances, class_name: "User"
end

class Attendance
  belongs_to :attended_event, class_name: "Event"
  belongs_to :attendee, class_name: "User"
end

クラス名のエイリアシングを試したのはこれが初めてで、機能させるのに苦労しています。問題が関連付けの定義方法にあるのか、それとも他の場所にあるのかはわかりません。

私の関連付けは問題ないように見えますか? これを機能させるために必要なものを見落としていませんか?

私が抱えている問題は、出席モデルにユーザー ID が設定されていないことです。これはばかげた質問かもしれませんが、上記の私の関連付けを考えると、フィールド名は :user_id または :event_organizer_id である必要がありますか?

これに関する提案を本当に感謝します。ありがとう!

4

1 に答える 1

1

User と Event に指定するforeign_key

class User
  has_many :events

  has_many :attendances, foreign_key: :attendee_id
  has_many :attended_events, through: :attendances
end

class Event
  belongs_to :event_organizer, class_name: "User" 
  # here it should be event_organizer_id

  has_many :attendances, foreign_key: :attended_event_id
  has_many :attendees, through: :attendances
end

class Attendance
  belongs_to :attended_event, class_name: "Event" 
  # this should have attended_event_id

  belongs_to :attendee, class_name: "User"        
  # this should have attendee_id because of 1st param to belongs_to here is "attendee"
  # and same should be added as foreign_key in User model
  # same follows for Event too
end
于 2012-06-05T15:11:37.970 に答える