与Parent一起创建嵌套资源

时间:2017-02-24 19:12:46

标签: ruby-on-rails roles nested-resources

我有三个模型Session,Attendee,Role。 Attendee嵌套在Session中,Role是一个单独的模型。

我希望能够创建新会话,并且在创建会话时,会为具有角色“所有者”的会话创建与会者。

我在两件事上画了一个空白:

1)如何在创建

时向参加者添加参加者

2)如何找到角色“所有者”的ID并将其添加为参加者的参数。

期待您的回复!

:d

1 个答案:

答案 0 :(得分:0)

几种选择。

将其添加到会话的after_createbefore_create回调。

class Session
   after_create :create_attendee

   def create_attendee
      Attendee.create(session: this)
   end
end

class Session
   before_create :build_attendee

   def build_attendee
      this.attendees << Attendee.new(...)
   end
end

在创建会话对象时显式创建

session = Session.new(..)
session.attendees << Attendee.new(..)
session.save
相关问题