Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's several ways to tackle this. The approaches explained below are for Rails 3.1</p> <p>Call render directly in your method(this approach is helpful for a JSON API only approach. Since html rendering will be non-existant):</p> <pre><code>def newItem @Item = Item.create(:description =&gt; params[:description], :type_id =&gt; params[:type]) render json: @Item end </code></pre> <p>Use a respond_do block:</p> <pre><code>def newItem @Item = Item.create(:description =&gt; params[:description], :type_id =&gt; 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 </code></pre> <p>Teach your controller the response formats you desire:</p> <pre><code>class ContributionsController &lt; ApplicationController # Set response format json respond_to :json ... def newItem @Item = Item.create(:description =&gt; params[:description], :type_id =&gt; params[:type]) respond_with @Item #=&gt; /views/contributions/new_item.json.erb end </code></pre> <p>Possible "gotcha"... </p> <p>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)</p> <p>Add the following to your model. It'll include the validation failures in an errors hash within the json response</p> <pre><code> class Item &lt; ActiveRecord::Base ... # includes any validation errors in serializable responses def serializable_hash( options = {} ) options = { :methods =&gt; [:errors] }.merge( options ||= {} ) super options end </code></pre> <p>There's always more than one way to skin a cat. I hope this helps</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload