没有“将表格提交给模型”之类的东西。表单总是提交给您的控制器。
考虑到这一点,您可以重写控制器上的create
orupdate
方法来执行您想要的任何操作。
您的控制器将如下所示:
class RestaurantsController < ApplicationController
def update
@restaurant = Restaurant.find(params[:id])
unless @restaurant.update_attributes(params[:restaurant])
# error while saving: warn user, etc
return # stops execution
end
# restaurant was saved ok, do the additional things you want
StatusUpdate.create :user_id => @restaurant.user_id,
:comment => "I just ate @ #{@restaurant.name}"
flash[:notice] = 'Restaurant was successfully updated, and a status update was added.'
redirect_to :action => 'list'
end
end
然而,如果你的场景看起来很简单,你也可以在你的模型上使用 ActiveRecord 回调来解决这个问题:
class Restaurant < ActiveRecord::Base
after_save :append_status_update
private
def append_status_update
StatusUpdate.create :user_id => self.user_id,
:comment => "I just ate @ #{self.name}"
end
end