开发者

1 submit button for 2 models (fields_for) in Rails 2.3.9

开发者 https://www.devze.com 2023-01-23 19:08 出处:网络
I have 2 models that correspond to 2 separate db tables. model 1: status updates of a user ex. ( comment: hello | username: marc)

I have 2 models that correspond to 2 separate db tables.

model 1: status updates of a user ex. ( comment: hello | username: marc) model 2: restaurant names that a user has eaten at ( restaurant: KFC | username: marc)

I have 1 view that shows rest开发者_StackOverflowaurant websites generated from a Google search. A hidden form is also generated for each restaurant listed. When the user presses the "I ate here!" button, it submits this hidden form to the restaurants controller, then model 2, recording the users name and the resturant he ate at.

I want to use the "I ate here!" button to ALSO post a status update of the restaurant name to model 1.

this should be done with fields_for, but the 2 models don't have a relationship with each other.. that I see..

How can I make this happen?

here is my pastie: http://www.pastie.org/1280923

I hope thats clear!


There's no such thing as "submits the form to a model". Forms are always submitted to your controller.

With that in mind, you can just override the create or update method on your controller to perform any action you want.

Your controller will look like this:

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

However, if your scenario is as simple as it looks, you can also solve this using an ActiveRecord callback on your model:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消