【问题标题】:Retrieve associations in AngularJS & Rails using ngResource使用 ngResource 检索 AngularJS 和 Rails 中的关联
【发布时间】:2015-08-29 10:28:38
【问题描述】:

我有记录类别模型:

class Record < ActiveRecord::Base
    belongs_to :category
end

class Category < ActiveRecord::Base
    has_many :records
end

Category 模型有一个 name 字段,应该用于显示。我正在使用 ng-repeat 显示记录,'record.category.name' 导致我的页面中断:

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

如何正确检索“record.category”,以便像上面那样使用“名称”字段?到目前为止,使用 ngResource 并没有填充关联。

我正在使用 ngResource 检索 Record 模型:

            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;
            });

如何在 AngularJS 中检索此模型,以便关联数据也可用于显示?

感谢任何帮助。

编辑:

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])

【问题讨论】:

    标签: ruby-on-rails angularjs ruby-on-rails-4 associations ngresource


    【解决方案1】:

    这并不是真正的 Angular 问题,而是 Rails(和 API 设计)问题。我说 API 设计的原因是因为根据用例,客户端获取所有类别并在前端完成将类别与记录匹配的工作可能会更有效。也就是说,要做你想做的事,你需要改变你的Rails app

    链接答案中的修改代码:

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

    当我在做 Rails 时,你可以在 find 调用中调用 :include,但我已经有一段时间没有使用 Rails了。我不知道这是否仍然是最好的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多