简体   繁体   中英

How to create a rails api that routes different urls

Am new to rails I want to perform a get request in different urls such as http://website.com/api/example1 http://website.com/api/example2 http://website.com/api/example3 http://website.com/api/example4

And how can i set session data to be accessed across all controllers in the app

You can simply set your session value in your code as so:

session[:some_value] = 'This is a session value'

What you do not want to do is store large amounts of data into your session. This will have huge performance implications. If you need to store large amounts of data, I would suggest a model to store it in within the database.

Although, I would question why you are setting things in the session for URL access?

http://guides.rubyonrails.org/security.html#sessions

You can add something like following at your routes.rb :

scope "api",:module => "api" do
  get 'example1' => 'exact_data#example1', :as => 'api_example1'
  get 'example2' => 'exact_data#example2', :as => 'api_example2'
  get 'example3' => 'exact_data#example3', :as => 'api_example3'
end

So your controller should have:

class Api::ExactDataController < ApplicationController
    def example1 
        #...
    end
    def example2 
        #...
    end
    def example3 
        #...
    end
end

If you have common session logic that you want to access and use from all controllers then you can put them at your application_controller.rb as by default it is parent of all other controllers that you create.

For example if you put a current_user method at ApplicationController then you would have current_user method in all your controllers:

class ApplicationController < ActionController::Base
    protect_from_forgery

private

    def current_user
      @current_user ||= User.find_by_username(session[:username]) if session[:username]
    end

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM