2016-07-18 2 views
0

메뉴 항목에서 모델 협회레일 Has_many 및 Belongs_to

class MenuItem < ActiveRecord::Base 
    has_many :menu_tags 
end 

메뉴 태그

class MenuTag < ActiveRecord::Base 
    belongs_to :menu_item 
end 

마이그레이션 : 나는 쿼리를 실행 그래서 만약 내가이 마이그레이션을 변경할 수있는 방법

class CreateMenuItems < ActiveRecord::Migration 
    def change 
    create_table :menu_items do |t| 
     t.string :name 
     t.string :description 
    end 
    end 
end 


class CreateMenuTags < ActiveRecord::Migration 
    def change 
    create_table :menu_tags do |t| 
     t.string :name 
     t.integer :menu_item_id 

     t.timestamps null: false 
    end 
    end 
end 

메뉴 항목, 모든 메뉴 태그를 볼 수 있습니까? 원하는 쿼리 :

MenuItem.first = #<MenuItem id: 2, name: "Steak", description: "Shank, medium-rare", menu_tags = [#<MenuTag id: 1, name: "Spicy">, #<MenuTag id: 4, name: "Salty">], created_at: "2016-07-18 02:54:55", updated_at: "2016-07-18 02:54:55"> 
+1

'MenuItem.joins (: Menutag) .all' 시도해보십시오 – uzaif

답변

2

이미 액티브를 사용하면 같은 호출하여 관련된 모든 모델을 볼 수 위의와

MenuItem.first.menu_tags 

문제를, 데이터베이스 쿼리는 충분히 효율적으로하지 않을 수 있습니다. 이러한 액티브가 연결을 eager_load하는 방법을 제공 해결하기 : 이것은 액티브/데이터베이스 측면에서 더 효율적입니다

MenuItem.includes(:menu_tags).first.menu_tags 

. 빠르게 관찰 할 것

것은 관련 모델이 전화 할 때 콘솔에 표시되지 않는 것입니다 :

MenuItem.first = #<MenuItem id: 2, name: "Steak", description: "Shank, medium-rare", menu_tags = [#<MenuTag id: 1, name: "Spicy">, #<MenuTag id: 4, name: "Salty">], created_at: "2016-07-18 02:54:55", updated_at: "2016-07-18 02:54:55"> 

액티브 번호의 기본 동작 방법은 특성을 보여주는 것입니다 검사 때문이다 연관된 모델의 모델을 추가하지 않아도됩니다. 수 있습니다. look this up in the source code here..

참고 :이 인 텐트 메서드를 재정 의하여 관련 개체를 포함하여 사용자 고유의 동작을 정의 할 수 있습니다.

희망이 있습니다.

+0

와우, 설명에 너무 감사드립니다! 그것은 나를 대단히 도왔다! – user3007294