我正在努力在我的应用中创建购物清单,并且正在努力了解使用连接表在我的视图中返回所需的inventory_item属性的方法。我想在我的列表中返回inventory_item的这些属性 - :price,:vendor,:name,:details,:brand。我有这些相关的模型:
在视图中使用这样的连接表的最佳做法是什么?你能建议一些简单的控制台测试来熟悉这种做法吗?提前谢谢!
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 :(得分:0)
您可以执行类似
的操作<ul>
<% @shopping_list.inventory_items.each do |item| %>
<li><%= item.price %></li>
<li><%= item.vendor %></li>
<% end %>
</ul>
等等。与@vendor.items