0

Just working on Ruby on Rails for the first time.

In my controller, am saving new users informations as follows and everything works fine via code below

 # POST /users
  def create
    @user = User.new(user_params)

    if @user.save
      session[:user_id] = @user.id   
      redirect_to @user, notice: 'User was successfully created.'
    else
      render :new
    end
  end

Now I need to get messages responses via json when form is submitted so that I can access it from my frontend. To this effect, I have added code below but it shows error

ActionController::UnknownFormat

I have reference solution found here but cannot get it to work

link

  # POST /users
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        session[:user_id] = @user.id   
        format.json { render json: @user, message: 'User was successfully created.' }  
      else
        #render :new

        format.json { render json: @user, message: 'User cannot be created.' }    
      end
    end 
  end
Nancy Moore
  • 2,322
  • 2
  • 21
  • 38
  • I'm guessing you are not sending the request for the correct format. You can verify this by looking at the logs which should say something like `Processing by UsersController#create as HTML`.You either need to send the request to `/users.json` or send a `content-type=application/json` header. – max Apr 12 '19 at 22:53
  • Sir format.html is working but format.json is what that is causing the error. Please is there any place i need some configurations. between thanks – Nancy Moore Apr 13 '19 at 00:55
  • How are you sending the request? Please edit your question with a https://stackoverflow.com/help/mcve – max Apr 13 '19 at 13:13

2 Answers2

0

Resolved by adding this to your routes config

resources :entries, defaults: { format: 'json' }

stackoverflow source

Nancy Moore
  • 2,322
  • 2
  • 21
  • 38
0

In your case, no need to write it down like this. Or use respond_to

Simply write it down if you are using rails 5:

# POST /users
def create
    @user = User.new(user_params)

    if @user.save
       session[:user_id] = @user.id   
       render json: @user, message: 'User was successfully created.' 
     else
       #render :new

       render json: @user, message: 'User cannot be created.' 
  end
end

And Mention in routes.rb file

resources :tasks, defaults: {format: :json}

If you are also defining namespace in routes.rb file then

namespace :api, defaults: {format: :json} do
   resources :tasks1
   resources :tasks2
   .............
end
Pragya Sriharsh
  • 529
  • 3
  • 6