2013-08-13 5 views
0

내 앱에서 쇼핑 목록을 만드는 중이며 조인 테이블을 사용하여 내 뷰에서 원하는 인벤토리 속성 인 inventory_item을 반환하는 방법을 이해하는 데 어려움이 있습니다. 나는 가격, : 공급 업체, : 이름, : 세부 사항, : 브랜드 등 내 목록에서 inventory_item의 이러한 속성을 반환하고 싶습니다. 이 관련 모델을 가지고 있습니다 :보기에서 HABTM 조인 테이블에 액세스

보기에서 이와 같은 조인 테이블을 사용하는 것이 가장 좋은 방법은 무엇입니까? 연습에 익숙해 지도록 간단한 콘솔 테스트를 제안 할 수 있습니까? 미리 감사드립니다!

class InventoryItem < ActiveRecord::Base 
    belongs_to :item, :foreign_key => :item_id 
    belongs_to :vendor 
    has_and_belongs_to_many :shopping_lists 
end 

class Item < ActiveRecord::Base 
    has_many :inventory_items 
    has_many :vendors, through: :inventory_items 
end 

class ShoppingList < ActiveRecord::Base 
    has_and_belongs_to_many :inventory_items 
    belongs_to :user 
end 

class Vendor < ActiveRecord::Base 
    has_many :inventory_items 
    has_many :items, through: :inventory_items 
    has_many :shopping_list_items 
end 

class User < ActiveRecord::Base 
has_many :shopping_lists 
end 

덕분에 내가 가입 테이블에 따라 설정 얻을 수 있었다 @Grantovich하기 :

class ListItemJoin < ActiveRecord::Migration 
    def change 
    create_table :inventory_items_shopping_lists, id: false do |t| 
     t.references :inventory_item 
     t.references :shopping_list 
    end 

    add_index :inventory_items_shopping_lists, :inventory_item_id 
    add_index :inventory_items_shopping_lists, :shopping_list_id 
    add_index :inventory_items_shopping_lists, [:inventory_item_id, :shopping_list_id], unique: true, :name => 'my_index' 
    end 
end 

내가 RoR에에 약간 새로운 오전, 그래서 어떤 비판이나 제안은 감사합니다, 감사합니다!

답변

0

당신은 너무에

<ul> 
    <% @shopping_list.inventory_items.each do |item| %> 
    <li><%= item.price %></li> 
    <li><%= item.vendor %></li> 
    <% end %> 
</ul> 

과 같은 작업을 수행 할 수 있습니다. 같은 일로 @vendor.items

+0

감사합니다. 감사합니다. @ 섀도우. 아직 조인 테이블에 아무 것도 없다는 것을 분명히해야합니다. 그래서 내가하려는 것은 사용자가 쇼핑 목록에 항목을 추가하여 새로운 항목을 생성하도록하는 것입니다. 제출 버튼과 조치가 어떻게 생겼는지에 대한 도움이 필요하십니까? – settheline

관련 문제