在 rails 中对单个表单提交调用 2 post 控制器方法
Call 2 post controller methods on single form submission in rails
我有一个用例,我需要在单个表单提交时创建 2 个元组(一个在邀请中,一个在通知中 table)(操作定向到 Invitation#create)。
如何从 Invitation create 调用 Notification create 方法以在 Notification table 中创建新元组。
PS: 邀请和通知没有关系。
您不会转到通知创建操作,您只需在邀请创建中执行即可。下面的代码将使用共享关注方法,下面将对其进行解释:
class InvitationsController < ApplicationController
include Notifications
#....
def create
invitation = Invitiation.create(invitation_params)
create_notification(invitation)
end
private
def invitation_params
# strong params code
end
end
因此,如果您有第二个 controller/model,例如回复:
class RsvpsController < ApplicationController
include Notifications
#....
def create
rsvp = Rsvp.create(rsvp_params)
create_notification(rsvp)
end
private
def rsvp_params
# strong params code
end
end
然后在controllers/concerns目录下,你可以创建一个文件'notifications.rb'
module Notifications
extend ActiveSupport::Concern
def create_notification(object)
Notification.create(object_id: object.id, object_type: object_type)
end
end
我有一个用例,我需要在单个表单提交时创建 2 个元组(一个在邀请中,一个在通知中 table)(操作定向到 Invitation#create)。 如何从 Invitation create 调用 Notification create 方法以在 Notification table 中创建新元组。
PS: 邀请和通知没有关系。
您不会转到通知创建操作,您只需在邀请创建中执行即可。下面的代码将使用共享关注方法,下面将对其进行解释:
class InvitationsController < ApplicationController
include Notifications
#....
def create
invitation = Invitiation.create(invitation_params)
create_notification(invitation)
end
private
def invitation_params
# strong params code
end
end
因此,如果您有第二个 controller/model,例如回复:
class RsvpsController < ApplicationController
include Notifications
#....
def create
rsvp = Rsvp.create(rsvp_params)
create_notification(rsvp)
end
private
def rsvp_params
# strong params code
end
end
然后在controllers/concerns目录下,你可以创建一个文件'notifications.rb'
module Notifications
extend ActiveSupport::Concern
def create_notification(object)
Notification.create(object_id: object.id, object_type: object_type)
end
end