Question

I am working on creating shopping lists in my app and am struggling to understand the methods of using a join table to return my desired attributes of inventory_item in my views. I want to return these attributes of inventory_item in my lists - :price, :vendor, :name, :details, :brand. I have these relevant models:

What is the best practice for working with a join table like this in the view? Can you suggest some simple console testing to familiarize myself with the practice? Thanks in advance!

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

Thanks to @Grantovich I was able to get my join table set up accordingly:

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

I am newish to RoR, so any critiques or suggestions are appreciated, thank you!

Était-ce utile?

La solution

You can do something like

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

and so on. Same thing as @vendor.items

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top