1

I'm just starting out learning Angular and have watched Ryan Bates' Railscast, as well as read BerylliumWork's tutorial, but I'm still struggling to figure out how to access data from my Rails server.

I have a pretty straightforward use case here. I want to access a user's first_name in view.

Here is the view code:

 <div ng-controller="UserCtrl">
  {{user.first_name}}
 </div>

Here is the coffeescript file:

app = angular.module("app", ["ngResource"])
app.factory "User", ["$resource", ($resource) ->
  $resource("/users/:id", {id: "@id"}, {
    show: {method: "GET"}
    })
]

@UserCtrl = ["$scope", "User", ($scope, User) ->
  $scope.users = User.query()
  $scope.user = User.show(id: **1**)
]

Here is my controller:

def show
  respond_with User.find(params[:id])
end

As you can see, I have a hardcoded id in $scope.user and it shows up on the page. Similarly, if I use something like ng-app="user in users"...{user.first_name}, I get the full list of users.

How do I get one instance of user though? Using the instance variable, not my hardcoded "1"?

1 Answer 1

1

By default:

  • $resource.query() is for getting a list of objects.
  • $resource.get({params}) is for getting a single object

In your case, you need $scope.user = User.get({id: 1}).

Sign up to request clarification or add additional context in comments.

3 Comments

How do I make that "1" a variable, though? The code above pulls User 1 already. But what if I want user n?
User.query() fetches a list of all users (given that you not supply any filters to it, e.g. User.query({active: true})). This list is an array of object. Each object is a specific object, defined by how your response from the server looks like. It's than up to you to decide how do you want to go over this list in order to fetch (and possibly edit) each user. You might also use a separate route for fetching/showing/editing single user. You could accomplish that through a custom route defined in $routeProvider (e.g. when('/users/:id', {controller: 'UserCtrl', templateUrl: 'path_to_tpl'})).
That's what I needed to do - set up the $routeProvider. Thanks a lot, @Stewie! Victory is yours, indeed.

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.