2

我有 2 个模型对应于 2 个单独的数据库表。

模型1:用户ex的状态更新。(评论:你好|用户名:marc)模型2:用户吃过的餐厅名称(餐厅:肯德基|用户名:marc)

我有 1 个视图显示从 Google 搜索生成的餐厅网站。还会为列出的每家餐厅生成一个隐藏表格。当用户按下“我在这里吃了!” 按钮,它将这个隐藏的表单提交给餐厅控制器,然后是模型 2,记录用户姓名和他吃的餐厅。

我想用“我在这里吃饭!” 按钮还可以将餐厅名称的状态更新发布到模型 1。

这应该用fields_for来完成,但是这两个模型之间没有关系..我明白了..

我怎样才能做到这一点?

这是我的馅饼:http: //www.pastie.org/1280923

我希望那很清楚!

4

1 回答 1

1

没有“将表格提交给模型”之类的东西。表单总是提交给您的控制器。

考虑到这一点,您可以重写控制器上的createorupdate方法来执行您想要的任何操作。

您的控制器将如下所示:

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
于 2010-11-08T07:20:37.887 回答