0

I have a method in my rails controller and in the controller I need to render the output as a message in json format.

def createItem
    @item = Item.new(params[:item])

    respond_to do |format|
      if @item.save
        format.json { render json: message: "Item is successfully Created" }
      else
        format.json { render json: @item.errors, status: :unprocessable_entity }
      end
    end
  end

But when I submit the form, the browser is displaying blank. I need to render the json text as above. How do I do it. Please help

2 Answers 2

2

You could change,

def createItem
  @item = Item.new(params[:item])

  respond_to do |format|
    if @item.save
      format.json { render json: message: "Item is successfully Created" }
    else
      format.json { render json: @item.errors, status: :unprocessable_entity }
    end
  end
end

To

def createItem
  @item = Item.new(params[:item])

  respond_to do |format|
    if @item.save
      json_string = {'message' => 'Item is successfully Created'}.to_json
      format.json { render :json => {item: @item, json_string}
    else
      format.json { render json: @item.errors, status: :unprocessable_entity }
    end
  end

end

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to see the JSON request you should have to give the .json at the end of your URL.

Suppose that you dont want to give the url, in your model you should type :

def as_json(options={})
    { :name => self.name }  # NOT including the email field
end

def as_json(options={})
    super(:only => [:name])
end

And then in your controller :

def index 
  @names = render :json => Name.all 
end

Then the JSON code will automatically come to picture without using .json.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.