Question

Working from the railscast #160 base code I've set up a very simple site that allows me to log in, out and register an account. (Its almost identical except that I've removed the 'username' from the users migrate table and relevant views so only an email address is required)

I'm now trying to create a new log in action so that I can log in via JSON.

I'd like to be able to send a get request to http://app:3000/apilogin?email=my@email.com&password=p4ssw0rd and have the rails app store the IP address the request came from (if the log in was correct) and send a relevant response (in JSON).

So far I have added a section to controllers/user_sessions_controller.rb so that it goes:

class UserSessionsController < ApplicationController
  #...
  def new_api
    respond_to do |format|
      format.json
    end
  end
end

To routes.rb:

map.apilogin "apilogin", :controller => "user_sessions", :action => "new_api"

But I'm at a loss as to what to put in views/user_sessions/new_api.json.rb! Can you help?

Was it helpful?

Solution

You don't need to define a view at all - just return appropriate json from the controller.

def new_api
  @user_session = UserSession.new({:email => params[:email], :password => params[:password]})
  respond_to do |format|
    if @user_session.save
      format.json { render :json => {:success => true} }
    else
      format.json { render :json => {:success => false, :message => 'incorrect username or password'}, :status => :unauthorized }
    end
  end
end

OTHER TIPS

You can do something like this:

  def new_api
    respond_to do |format|
      format.json { render :json => user.slice(:name).to_json }
    end
  end

Or you can also generate the JSON in views/user_sessions/new_api.json.erb as you would write normal erb code. Not a good idea though:

{"name":"<%= @user.name %>"}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top