代码之家  ›  专栏  ›  技术社区  ›  thedeepfield

Rails 2.3.9中2个型号(字段_for)的1个提交按钮

  •  2
  • thedeepfield  · 技术社区  · 15 年前

    我有两个模型,对应于两个单独的DB表。

    模型1:用户状态更新,例如(注释:hello用户名:marc) 模式2:用户吃过的餐厅名称(餐厅:kfc用户名:marc)

    我有一个视图显示了从谷歌搜索生成的餐馆网站。还为列出的每个餐厅生成隐藏表单。当用户按下“我在这里吃饭!”按钮,它将这个隐藏的表单提交给餐厅管理员,然后模型2,记录用户名和他吃的餐馆。

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

    这应该用字段“for”来完成,但这两个模型之间没有关系。我看到了……

    我怎样才能做到这一点?

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

    我希望清楚!

    1 回复  |  直到 15 年前
        1
  •  1
  •   Fábio Batista Raza Ahmed    15 年前

    create update

    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
    

    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
    
    推荐文章