Retrieve associations in AngularJS & Rails using ngResource

梦想的初衷 提交于 2019-12-25 04:18:19

问题


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.



来源:https://stackoverflow.com/questions/30819551/retrieve-associations-in-angularjs-rails-using-ngresource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!