1

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
1
  • Please show us the view for your index action. It's likely that you've not added extra parameters there. Commented Sep 26, 2014 at 6:43

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

gotit ..simple..i dint even realize that exists a file called index.json.jbuilder till now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.