我在后端使用Rails 4编写,而在Angular js中使用前端编写。我在使用关联时遇到麻烦。
我有两个模型:
class Record < ActiveRecord::Base
has_and_belongs_to_many :tags
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :records
end
我正在使用模型records_tags
连接两个模型Record
和Tag
。
在控制器中,我写道:
def index
records = Record.all.order('created_at DESC')
render json: {error:0, data: records}
end
视线中
<ul>
<li ng-repeat ="data in datas"> {{data.tags.name}}</li>
</ul>
虽然,我在控制器成功时使用了关系,但是我发送给查看的变量数据并不使用关系。
有人可以帮助我吗?
那很正常,当您在控制器中时,data
是ActiveModel对象的集合,因此关系在其中存在。但是当您导出为json时,您仅发送json对象。要包含在tags
其中records
,必须包含tags
在json
对象中。
def index
records = Record.all.order('created_at DESC')
render json: {error:0, data: records.as_json(include: :tags))}
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句