2015-11-05 77 views
0

我很困惑如何從角度前端的軌道中關聯模型中更好地更新數據(儘管這更像是軌道問題)。更新軌道中的關聯模型

說我有所謂的可投票模型的一些屬性(日期,結束日期)和的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 

我缺少什麼?我是否需要手動處理關聯的更新?這最好的做法是什麼?

謝謝!

回答

0

我認爲你的問題是因爲你需要允許votable_texts模型的嵌套參數。但是,當使用accepts_nested_attributes_forupdate時,Rails希望您通過voteable_texts_attributes以更新相關記錄。在這種情況下,您將擁有以下內容。

params.permit(:id, :start_date, :end_date, votable_texts_attributes: [:id, :voteable_id, :locale, :issue])

所以,你可能需要更新的節目操作使用voteable_texts_attributes或者如果不是你將不得不沿線某處改變帕拉姆關鍵。