관계

2012-09-16 3 views
0

의 모든 자식 요소를 파괴하는 방법을 나는관계

class List < ActiveRecord::Base 
    has_many :list_items 

class ListItem < ActiveRecord::Base 
    belongs_to :list 

내가 특정 유형의 모든 목록을 선택하고 모든 관련 list_items을 삭제할 수 있습니다. 나는지도와 다른 것들을 시도했지만 붙어 있습니다.

List.where('list_type_id=4').? 

나는 한 줄짜리지만 알아야 하나? 당신이에 연결을 설정합니다

class List < ActiveRecord::Base 
    has_many :list_items, :dependent => :destroy 

목록뿐만 아니라 모든 관련 항목을 삭제하고 싶다면

들으

** 편집 # 1 **

SyntaxError: (irb):94: syntax error, unexpected tCONSTANT, expecting ')' 
...ListItem.where('list_id = ?' List.where('list_type_id=4').id).... 
...        ^
(irb):94: syntax error, unexpected ')', expecting $end 
...ist.where('list_type_id=4').id).destroy_all 
...        ^
+0

어쩌면'List.where ('list_type_id = 4'). map (& : list_items) .flatten.destroy_all' 같은가요? –

+0

이것이 가장 비슷해 보이지만 나는이 오류 메시지를 받는다 : NoMethodError : 정의되지 않은 메쏘드'destroy_all for # '; 정말 aggrevating; thx – timpone

+0

그래, 그건 의미가있다. 그럼'destroy_all'을'each {| li | li.delete}'. –

답변

0

List.where('list_type_id=4').map(&:list_items).flatten.each {|li| li.delete } 

하지만 그래, Railsier 방식으로해야한다고 생각합니다.

+0

아니요, Joe Hoang 대답은 더 적절한 – ImranNaqvi

2

목록이 삭제되면 모든 list_item을 자동으로 삭제합니다. 그냥

ListItem.where('list_id = ?', List.find_by_list_type_id(4).id).destroy_all 

또는

List.find_by_list_type_id(4).list_items.destroy_all 
+0

후자와 비슷하지만 오류가 발생합니다 – timpone

+0

무엇이 오류입니까? –

+0

위 ^^, thx – timpone

0

이 시도 그 목록과 관련된 많은 ListItems 삭제하려면

List.where('list_type_id=4').destroy 

: 후세를 들어

class List < ActiveRecord::Base 
    has_many :list_items, :dependent => :delete_all 

List.where('list_type_id=4').list_items.clear 
+0

관련 항목을 삭제하고 목록과 관련 항목을 삭제하고 싶습니다. – timpone

+0

@timpone을 참조하십시오. – megas

+0

주사위가 없습니다. -지도 단계가 필요하다고 생각합니다. – timpone