在两个模型之间创建关联对象时,属性未知

时间:2018-06-28 10:55:14

标签: ruby-on-rails ruby-on-rails-5

因此,我有三个模型:UserEvent,它们具有通过has_many through进行的Attendance-关联。当在rails console --sandbox中创建用户与事件之间的关系时,例如user1.attended_events.build(event_id: event1.id),我在写unknown attribute 'event_id' for Event时也会得到event1.attendees.build(attendee_id: user1.id)unknown attribute 'attendee_id' for User

对于Attendance,我创建了一个这样的表:

class CreateAttendances < ActiveRecord::Migration[5.1]
  def change
    create_table :attendances do |t|
      t.references :event, foreign_key: true
      t.integer :attendee_id

      t.timestamps
    end
    add_index :attendances, :attendee_id
    add_index :attendances, [:event_id, :attendee_id], unique: true
 end
end

这是我的模型的样子(用户也可以创建事件):

用户模型:

class User < ApplicationRecord
   has_many :events, inverse_of: "creator", foreign_key: "creator_id" , dependent: :destroy

   has_many :attendances, class_name: "Attendance", inverse_of: "attendee", foreign_key: "attendee_id", dependent: :destroy
   has_many :attended_events, through: :attendances, source: :event
end

事件模型:

class Event < ApplicationRecord
    belongs_to :creator, class_name: "User", foreign_key: "creator_id"

    has_many :attendances
    has_many :attendees, through: :attendances
end

出勤模式:

class Attendance < ApplicationRecord
  belongs_to :event, inverse_of: :attendances
  belongs_to :attendee, class_name: "User", inverse_of: :attendances
end

提前谢谢!

1 个答案:

答案 0 :(得分:0)

当您运行event1.attendees.build(some_params)时,您试图建立一个新用户,是的,该用户模型没有attendee_id属性。

应为event1.attendances.build(attendee_id: user1.id)user1.attendances.build(event_id: event1.id)也是如此。

更新。

不确定我是否正确理解了您在评论中提出的问题,但我会尽力回答。

假设我们有一个userevent1event2实例以及user.attended_events == [event1, event2]user不想再参与event2,因此您需要销毁此关联。

User.attendances.find_by(event_id: event2.id).destroy

它将仅破坏Attendance实例,并变为user.attended_events == [event1]。并且在event2.attendees数组中将不再是user