Rahul Dess
Rahul Dess

Reputation: 2597

Getting json data from rails method

I think i am missing something silly here , but cannot figure out and its been more than an hour trying. So without wasting time ..

I want to fetch index action in Users controller using json.
For example localhost:3000/users.json right now gives me data ..

[{"id":17,"url":"http://localhost:3000/users/17.json"},{"id":16,"url":"http://localhost:3000/users/16.json"}]

But i have other attributes in User table like first_name and last_name etc.. which i would like to use from json.

How should i modify my existing method to get the required details.

  # GET /users
  # GET /users.json
  def index
   @users = User.all
  end


  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:avatar, :first_name, :last_name)
    end

Upvotes: 1

Views: 552

Answers (2)

Ryan Bigg
Ryan Bigg

Reputation: 107728

I think you just need to open app/views/users/index.jbuilder and add the attributes you want there.

Upvotes: 1

aelor
aelor

Reputation: 11126

change your index method to :

def index
 @users = User.all
 render :json => @users
end

this will show the json on localhost:3000/users

alternatively if you want it explicitly on localhost:3000/users.json

use respond_to like below:

def index 
  @users = User.all
  respond_to do |format|
     format.json { render :json => @users}
  end
end

Upvotes: 3

Related Questions