Reputation: 3132
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
Upvotes: 0
Views: 4948
Reputation: 6928
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
Upvotes: 2
Reputation: 11
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
.
Upvotes: 0