[英]updating associated model in rails
我很困惑如何最好地從帶有角度前端的Rails中的關聯模型中更新數據(盡管這實際上更多是Rails的問題)。
假設我有一個稱為votable的模型,其中有一些屬性(start_date,end_Date)和has_many文本(以不同的語言描述了votable)
class Votable < ActiveRecord::Base
has_many :votable_texts
accepts_nested_attributes_for :votable_texts
end
控制器中的show方法生成json數據,該數據用於angular中以構建表單:
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具有相同的結構)。
問題是votable模型的屬性確實得到了更新(例如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
我想念什么? 我需要手動處理關聯的更新嗎? 如何做到最好?
謝謝!
我認為您的問題是因為您需要允許votable_texts
模型的嵌套參數。 但是,在使用accepts_nested_attributes_for
和update
Rails會期望您傳遞voteable_texts_attributes
以便其更新關聯的記錄。 在這種情況下,您將擁有以下優勢。
params.permit(:id, :start_date, :end_date, votable_texts_attributes: [:id, :voteable_id, :locale, :issue])
因此,您可能需要更新show操作以使用voteable_texts_attributes
否則,您將不得不沿行中的某個位置更改參數鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.