检索AngularJS&中的关联使用ngResource的Rails [英] Retrieve associations in AngularJS & Rails using ngResource
问题描述
我有记录&类别模型:
class Record < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :records
end
类别模型具有一个名称字段,该字段应用于显示.我正在使用ng-repeat显示记录," record.category.name "导致我的页面中断:
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>
如何正确检索" record.category ",以便像上面一样可以使用名称"字段?到目前为止,尚未使用ngResource填充关联.
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.
我正在使用ngResource检索 Record 模型:
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;
});
如何在AngularJS中检索此模型,以便关联数据也可以显示?
How can I retrieve this model in AngularJS so that the association data are available for display as well?
感谢您的帮助.
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])
推荐答案
这并不是一个真正的Angular问题,而是一个Rails(和API设计)问题.我之所以说API设计,是因为根据使用情况,客户端获取所有类别并在前端进行工作以将类别与记录进行匹配可能会更加有效.也就是说,要执行您想做的事情,您需要更改您的 Rails应用程序.
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
返回时,在执行Rails时,您可以在 find
调用中执行:include
,但是我有一段时间没有使用Rails了.我不知道这是否仍然是最好的方法.
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.
这篇关于检索AngularJS&中的关联使用ngResource的Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!