Retrieve associations in AngularJS & Rails using n

2019-09-05 01:07发布

问题:

I have Record & Category model:

class Record < ActiveRecord::Base
    belongs_to :category
end

class Category < ActiveRecord::Base
    has_many :records
end

The Category model has a name field which should be used for display. I am using ng-repeat to display the records, the 'record.category.name' causes my page to break:

<tr ng-repeat="record in records">
    <td>{{record.category.name)}}</td>
    <td>{{record.description}}</td>
    <td>{{record.created_at | date:'medium'}}</td>
</tr>

How can I properly retrieve the 'record.category' so that the 'name' field is available as I have above? Using ngResource thus far has not populated the associations.

I am retrieving the Record model using ngResource:

            var Record = $resource('/records/:recordId', {
                recordId:'@id',
                format: 'json'
            }, {
                'save': {
                    method: 'PUT'
                },
                'create': {
                    method: 'POST'
                }
            });

            Record.query({
                    account_id: $routeParams.accountId
            }, function(results) {
                    return $scope.records = results;
            });

How can I retrieve this model in AngularJS so that the association data are available for display as well?

Any help is appreciated.

Edit:

index.json.jbuilder

json.array! @records, partial: 'record', as: :record

_record.json.jbuilder

json.(record, :id, :account_id, :user_id, :amount, :date, :description, :is_expense, :category_id, include: [:category])

回答1:

This isn't really an Angular issue, it's a Rails (and API design) issue. The reason I say API design is because depending on the use case it may be more efficient for the client to fetch all categories and do the work in the front end to match categories to records. That said, to do what you're trying to do you will need to change your Rails app.

Modified code from the linked answer:

def show
  @record = Record.find(params[:id])
  respond_to do |format|
    format.json { render :json => @record.to_json(:include => :category) }
  end
end

Back when I was doing Rails you could do the :include in the find call but I haven't done Rails for some time. I don't know if that's still the best way to do it.