我正在我的应用程序中创建购物清单,并且正在努力理解使用连接表在我的视图中返回我想要的 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 很陌生,因此感谢您提出任何批评或建议,谢谢!