Question

If I have a HABTM join table called, :inventory_items_shopping_lists, how do I create and call records in this table? I do not have a join model. The two joined models are :inventory_items and :shopping_lists. I'd like to be able to have a user add :inventory_items to their :shopping_lists. Thanks in advance!

EDIT

Here are the relevant models and my goal:

class InventoryItem < ActiveRecord::Base

    belongs_to  :item, :foreign_key => :item_id
    belongs_to  :vendor
    has_many    :list_items
end

class ListItem < ActiveRecord::Base
    belongs_to  :inventory_item, :foreign_key => :item_id
    belongs_to  :shopping_list
end

class ShoppingList < ActiveRecord::Base
    has_many :list_items
    belongs_to  :user, :foreign_key => :user_id
end

I'm attempting to have a :user add :inventory_items to a :shopping_list where they will become :list_items. list_items have almost identical attributes of :inventory_items, so I will likely just reference those attributes through association than by duplicating the attributes in the :list_items table. Thoughts or suggestions on this? I'm newish to RoR so I appreciate any feedback on any part of this plan. Thanks!

Était-ce utile?

La solution

how do I create and call records in this table?

You basically don't with a HABTM association type. If you want to store more state on the join table than you will need to use a standard has_many (and maybe a has_many :through) so you can manipulate the underlying join model.

For this reason I have never been a fan of HABTM and in fact I have a handful of large Rails apps in production and I have never used HABTM myself.

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