2013-11-04 17 views
1

爲什麼使用collection_singular_ids = IDS VS update_attributes方法(:collection_ids)

@thing.tag_ids = params[:thing][:tag_ids] 

在數據庫中保存一次的關係,但

@thing.update_attributes(params[:thing][:tag_ids]) 

不一樣,如果驗證失敗?

@thing.update_attributes(params[:thing][:tag_ids]) 

相同

@thing.tag_ids = params[:thing][:tag_ids] 
@thing.save 

不是嗎?

+2

'update_attribute'如何知道更新'tag_ids'?我認爲你在那裏有一些錯誤。 –

+0

'update_attributes'期望一個或多個鍵/值對。你只有價值輸入,沒有鑰匙。 –

回答

1

您是還挺正確的,下面的兩個語句完全相同的:

# save 
@thing.key = value 
@thing.save 

# update 
@thing.update_attributes({key: value}) 

與您的代碼的問題是,你有語法問題,你想:

@thing.update_attributes({tag_ids: params[:thing][:tag_ids]}) 
0

繼承人的解決方案似乎,第一種方法是使用update_attribute更新單個屬性,因此驗證永遠不會執行。但是,我們知道驗證的的update_attributes情況下始終執行

在這裏閱讀更多: - http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_attribute

+0

是的,但上面的兩個註釋也是正確的,你必須故意或錯誤地將@ tag_id從@thing中刪除。update_attributes({tag_ids:params [:thing] [:tag_ids]})。因爲沒有這個,你的程序肯定會有錯誤 – Akshat

0

我也有這樣的行爲掙扎......

代碼:

@thing.tag_ids = params[:thing][:tag_ids] 

在DB ad hoc中進行更改,並且它不會調用驗證,因此:

@thing.update_attributes(params[:thing][:tag_ids]) 

@thing.tag_ids = params[:thing][:tag_ids] 
@thing.save 

總之不同:

@thing.tag_ids = params[:thing][:tag_ids] # makes changes in DB w/o validations 
@thing.save # runs validations before making changes to DB 

我也詢問是否使用時,有可能運行驗證:

@instance.collection_singular_ids = other_singular_ids 

作爲一個快速解決我加覆蓋方法父模型('東西')像這樣:

def tag_ids=(ids) 
    super 
rescue ActiveRecord::RecordInvalid => e 
    self.errors.add(:base, e.message) 
end 

和驗證,以防止在標籤重複加入模型,像這樣:

validates :tag_id, :uniqueness => {:scope => :thing_id} 

有沒有人有一個更好的解決?

相關問題