render json as output in rails controller - ruby-on-rails-3

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

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

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.

Related

Gmaps4rails are not updating when address field is changed

I am using Gmaps4rails API. But whenever I update or edit the address, gmaps4rails still points to the old address. I am new to rails, so am not sure what is the mistake.
Below is my Controller.rb file
def show
if current_user.Company.nil?
#estate = current_user.estates.find(params[:id])
else
#estate = Estate.find(params[:id])
end
respond_to do |format|
format.html # show.html.erb
format.json { render json: #estate }
end
end
def new
##key = params[:user_id]
#master = ##key
#estate = Estate.new
#json = #estate.all.to_gmaps4rails
respond_to do |format|
format.html # new.html.erb
format.json { render json: #estate }
end
end
def edit
#estate = Estate.find(params[:id])
#json = #estate.to_gmaps4rails
end
def create
# #estate = Estate.new(params[:estate])
if current_user.Company.nil?
#estate = current_user.estates.build(params[:estate])
else
serve = User.find(##key)
#estate = Estate.new(params[:estate])
#estate.user_id = serve.id
#estate.Mgmt = current_user.Company
end
respond_to do |format|
if #estate.save
if current_user.Company.nil?
if #estate.companyemail = ''
##
else
EstateMailer.company_confirmation(#estate).deliver
end
end
format.html { redirect_to #estate, notice: 'Property details were successfully updated.' }
format.json { render json: #estate, status: :created, location: #estate }
else
format.html { render action: "new" }
format.json { render json: #estate.errors, status: :unprocessable_entity }
end
end
end
def update
#estate = Estate.find(params[:id])
#json = Estate.all.to_gmaps4rails
respond_to do |format|
if #estate.update_attributes(params[:estate])
format.html { redirect_to #estate, notice: 'Property details were successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #estate.errors, status: :unprocessable_entity }
end
end
end
Try this as per SO post
You'll need something like this in your model
:check_process : true/false (if set to false, geocoding will be made at every save/update)
:checker : string (only if check_process is true), could be a method or a db column boolean
More info here. Remember, Google is your friend.

Rails app generating wrong :id in parent controller

I am creating a very basic rails app for the first time with 2 resources, Departments(depts) and Members. I believe I have used nested resources correctly, but for some reason after running rails server, the :id for the parent resource is not being generated/passed correctly. Root is the depts#index and from here I can do new and edit using _form.haml rendered in the new and edit views. However, when I do /depts/3 I get error with "can't find dept with id=3". Clicking through to edit from index gives me /depts/63/edit in the URL - I'm not sure where this id=63 has come from. Trying to get to 'show' action by typing /dept/63 in the URL does not work. I created Depts on it's own at first, got it working with all actions and views, something has gone wrong since I added Members resource.
routes.rb
resources :depts do
resources :members
end
depts_controller.rb
def index
#depts = Dept.all
respond_to do |format|
format.html
format.json { render :json => #depts }
end
end
def show
#dept = Dept.find(params[:dept_id])
respond_to do |format|
format.html
format.json { render :json => #dept }
end
end
def new
#dept = Dept.new(params[:dept])
respond_to do |format|
format.html
format.json { render :json => #dept }
end
end
def create
#dept = Dept.new(params[:dept])
respond_to do |format|
if #dept.save
format.html { redirect_to :action => 'index' }
format.json { render :json => #dept }
else
format.html { render :action => 'new' }
format.json { render :json => #dept }
end
end
end
def edit
#dept = Dept.find(params[:id])
end
def update
#dept = Dept.find(params[:id])
respond_to do |format|
if #dept.update_attributes(params[:dept])
format.html { redirect_to :action => 'index'}#, :id => #dept }
format.json { render :json => #dept }
else
format.html { redirect_to :action => 'edit' }
format.json { render :json => #dept }
end
end
end
def destroy
#dept = Dept.find(params[:id])
#dept.destroy
respond_to do |format|
format.html { redirect_to :action => 'index' }
format.json { render :json => #dept }
end
end
end
show.haml
%p= #dept.name
%p= link_to "back", {:action => 'index'}
index.haml
%h1 DEPARTMENTS
%ol
- #depts.each do |d|
%li= link_to d.name
%p= link_to 'edit department', edit_dept_path(d)
%p= link_to 'get rid of department!', d, :method => :delete, :id => d.id
%br
%p= link_to "ADD A NEW DEPARTMENT", new_dept_path
in show method change:
#dept = Dept.find(params[:dept_id])
to:
#dept = Dept.find(params[:id])
and in new method change:
#dept = Dept.new(params[:dept])
to just:
#dept = Dept.new

Don't know how to make search form in rails 3

I need a search form in my rails 3.2.3 application, but i don't know how to do this, yesterday i had it fixed but then i deleted it :(.
Here are my Controller and Model:
Controller
class BedrijfsgegevensController < ApplicationController
def index
#bedrijfsgegevens = Bedrijfsgegeven.all
#bedrijfsgegevens = Bedrijfsgegeven.search(params[:search])
respond_to do |format|
format.html # index.html.erb
format.json { render json: #bedrijfsgegevens }
end
end
# GET /bedrijfsgegevens/1
# GET /bedrijfsgegevens/1.json
def show
#bedrijfsgegeven = Bedrijfsgegeven.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #bedrijfsgegeven }
end
end
# GET /bedrijfsgegevens/new
# GET /bedrijfsgegevens/new.json
def new
#bedrijfsgegeven = Bedrijfsgegeven.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #bedrijfsgegeven }
end
end
# GET /bedrijfsgegevens/1/edit
def edit
#bedrijfsgegeven = Bedrijfsgegeven.find(params[:id])
end
# POST /bedrijfsgegevens
# POST /bedrijfsgegevens.json
def create
#bedrijfsgegeven = Bedrijfsgegeven.new(params[:bedrijfsgegeven])
respond_to do |format|
if #bedrijfsgegeven.save
format.html { redirect_to #bedrijfsgegeven, notice: 'Bedrijfsgegeven was successfully created.' }
format.json { render json: #bedrijfsgegeven, status: :created, location: #bedrijfsgegeven }
else
format.html { render action: "new" }
format.json { render json: #bedrijfsgegeven.errors, status: :unprocessable_entity }
end
end
end
# PUT /bedrijfsgegevens/1
# PUT /bedrijfsgegevens/1.json
def update
#bedrijfsgegeven = Bedrijfsgegeven.find(params[:id])
respond_to do |format|
if #bedrijfsgegeven.update_attributes(params[:bedrijfsgegeven])
format.html { redirect_to #bedrijfsgegeven, notice: 'Bedrijfsgegeven was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #bedrijfsgegeven.errors, status: :unprocessable_entity }
end
end
end
# DELETE /bedrijfsgegevens/1
# DELETE /bedrijfsgegevens/1.json
def destroy
#bedrijfsgegeven = Bedrijfsgegeven.find(params[:id])
#bedrijfsgegeven.destroy
respond_to do |format|
format.html { redirect_to bedrijfsgegevens_url }
format.json { head :no_content }
end
end
end
Model
class Bedrijfsgegeven < ActiveRecord::Base
def search
#search = Bedrijfsgegeven.search() do
keywords(params[:search])
end
end
def self.search(search)
if search
find(:all, :conditions => ['Voornaam LIKE ?', "%#{search}%"])
else
find(:all)
end
end
validates :voornaam,
:achternaam,
:woonplaats,
:telefoon,
:website,
:email,
:presence => true
attr_accessible :achternaam, :email, :telefoon, :voornaam, :website, :woonplaats
end
i hope someone could help me out with this.
Grtz Kees
Have you read / watched the following railscast:
http://asciicasts.com/episodes/240-search-sort-paginate-with-ajax
Helps me every time I need basic search
I will recommend you to start using repositories which will make you safe from these incidental delete. You can get 5 free repositries at bitbucket.org. Both git and mercurial are awesome.

Send JSON to Rails REST API

I have a Rails application with articles and users.
So i want that a user can login out from an client application with json object and get all the article also with a json object.
But, I have some problems. Console output:
Started POST "/articles" for 127.0.0.1 at 2012-03-30 17:29:25 +0200
Processing by ArticlesController#create as JSON
Parameters: {"id"=>1, "article"=>{"id"=>1}}
WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 1ms
And here the Controler:
class ArticlesController < ApplicationController
before_filter :authenticate_user!, :except => [:show, :index]
# GET /articles
# GET /articles.json
def index
#articles = Article.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #articles }
end
end
# GET /articles/1
# GET /articles/1.json
def show
#article = Article.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #article }
end
end
# GET /articles/new
# GET /articles/new.json
def new
#article = Article.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #article }
end
end
# GET /articles/1/edit
def edit
#article = Article.find(params[:id])
end
# POST /articles
# POST /articles.json
def create
#article = Article.new(params[:article])
respond_to do |format|
if #article.save
format.html { redirect_to #article, notice: 'Article was successfully created.' }
format.json { render json: #article, status: :created, location: #article }
else
format.html { render action: "new" }
format.json { render json: #article.errors, status: :unprocessable_entity }
end
end
end
# PUT /articles/1
# PUT /articles/1.json
def update
#article = Article.find(params[:id])
respond_to do |format|
if #article.update_attributes(params[:article])
format.html { redirect_to #article, notice: 'Article was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #article.errors, status: :unprocessable_entity }
end
end
end
# DELETE /articles/1
# DELETE /articles/1.json
def destroy
#article = Article.find(params[:id])
#article.destroy
respond_to do |format|
format.html { redirect_to articles_url }
format.json { head :no_content }
end
end
end
And the Model:
class Article < ActiveRecord::Base
end
The JSON that I send looks like this:
{
"id" : 1
}
Routes
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
root / articles#index
Now my quesiton: is my JSON object wrong or am I missing something, like the CSRF token?
You need to make sure the CSRF token is submitted with each JSON HTTP Request. This is how I do it:
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
});

rails redirect or render with a specific verb

I want to redirect to a resource index when a new item is created
Here is a piece of the controller:
def create
#asset = Asset.new(params[:asset])
#assets = Asset.all
respond_to do |format|
if #asset.save
format.html { render :action => 'index' } ##########
format.xml { render :xml => #asset, :status => :created, :location => #asset }
else
format.html { render :action => "new" }
format.xml { render :xml => #asset.errors, :status => :unprocessable_entity }
end
end
end
The line i'm interested is marked ##########
i've tried
format.html { redirect_to(assets_url) }
and some other stuff
It redirects to the right place and creates the item fine, the problem is that i cant get it to not POST. I need to get it to GET because otherwise it does some horribly screwy things to my view.
redirect_to :action => :index Or redirect_to assets_url should work for you. Also, index action is always GET request. Do rake routes to see what kind of request happens for each action in your controller.