我正在使用Rails 4写入后端和角度js来编写前端。我很难使用关联。
我有两种模式:
setOnClickListener
我正在使用模型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
虽然,我在控制器成功中使用关系,但是我发送到视图的可变数据我不使用它们的关系。
任何人都可以帮助我?
答案 0 :(得分:0)
多数民众赞成正常,当您在控制器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