Mau Ruiz
Mau Ruiz

Reputation: 777

Get Params from ajax response Rails

I created a new action in the "contributions" controller like this

def newitem
    @Item = Item.new(:description => params[:description], :type_id => params[:type])
    if @Item.save
     #Magic supposed to happen here
   end
  end

So in this action I create a new "Item" and what I want to achieve is to get the id from the created item in an AJAX response, so I can use it in the same view the "item" is created...

1st question, how do I send back from the controller the params of the created item? 2nd I know how to handle Ajax requests but how do I handle an Ajax response to the first request...

Perhaps I am over thinking the solution but just cant figure out how to do it. Thanks in advance.

Upvotes: 2

Views: 959

Answers (1)

offbyjuan
offbyjuan

Reputation: 146

There's several ways to tackle this. The approaches explained below are for Rails 3.1

Call render directly in your method(this approach is helpful for a JSON API only approach. Since html rendering will be non-existant):

def newItem
    @Item = Item.create(:description => params[:description], :type_id => params[:type])
    render json: @Item
end

Use a respond_do block:

def newItem
  @Item = Item.create(:description => params[:description], :type_id => params[:type])

    respond_to do |format|
    if @Item.save
      format.html { redirect_to @Item, notice: 'Item was successfully created.' }
      format.json { render json: @Item, status: :created, location: @Item 
    else
      format.html { render action: "new" }
      format.json { render json: @Item.errors, status: :unprocessable_entity }
    end
  end
end

Teach your controller the response formats you desire:

class ContributionsController < ApplicationController
  # Set response format json
  respond_to :json

  ...

  def newItem
    @Item = Item.create(:description => params[:description], :type_id => params[:type])
    respond_with @Item  #=> /views/contributions/new_item.json.erb
  end

Possible "gotcha"...

If you have validation failures on Item create you will not get the id back, nor will it report a failure (other than the http response code)

Add the following to your model. It'll include the validation failures in an errors hash within the json response

 class Item < ActiveRecord::Base

   ...

   # includes any validation errors in serializable responses 
   def serializable_hash( options = {} ) 
     options = { :methods => [:errors] }.merge( options ||= {} )
     super options
   end

There's always more than one way to skin a cat. I hope this helps

Upvotes: 1

Related Questions