我很困惑如何从角度前端的轨道中关联模型中更好地更新数据(尽管这更像是轨道问题)。更新轨道中的关联模型
说我有所谓的可投票模型的一些属性(日期,结束日期)和的has_many文本(在不同语言的可投票的描述)
class Votable < ActiveRecord::Base
has_many :votable_texts
accepts_nested_attributes_for :votable_texts
end
在我的控制器的显示方法产生,我使用JSON数据在角构建形式:
def show
respond_to do |format|
format.json {
render :json => @votable.to_json(
:except => [:created_at, :updated_at],
:include => {
:votable_texts => {
:except => [:created_at, :updated_at]
}
}
)
}
end
end
这产生类似以下JSON:
{
"id": 2,
"start_date": "2015-02-05T00:00:00.000Z",
"end_date": "2016-02-02T00:00:00.000Z",
"votable_texts": [
{
"id": 6,
"votable_id": 2,
"locale": "nl",
"issue": "Test"
},
{
"id": 2,
"votable_id": 2,
"locale": "en",
"issue": "Test"
}
]
}
在角度方面,我将这个json读入一个变量,并使用ng-model将这些数据绑定到我的表单。当用户点击保存按钮时,我使用$ http.put将这些数据发回到rails(与由rails生成的json具有相同的结构)。
问题是可投票模型的属性确实得到更新(例如start_date),但嵌套的votable_texts模型中的属性未更新。
控制器看起来像这样的相关作品:
def update
respond_to do |format|
if @votable.update(votable_params)
format.json { render :show, status: :ok, location: @votable }
else
format.json { render json: @votable.errors, status: :unprocessable_entity }
end
end
end
private
def votable_params
params.permit(:id, :start_date, :end_date, :votable_texts)
end
我缺少什么?我是否需要手动处理关联的更新?这最好的做法是什么?
谢谢!