database - Creating an auto-updating list in Rails -


i have 3 relevant models:

class inventoryitem < activerecord::base     belongs_to  :item, :foreign_key => :item_id     belongs_to  :vendor     has_many    :shopping_list_items  class shoppinglist < activerecord::base     has_many    :shopping_list_items     belongs_to  :user end  class shoppinglistitem < activerecord::base   belongs_to    :shopping_list   belongs_to    :inventory_item end 

what trying create sidebar shopping list autoupdate shoppinglistitem attributes (specifically price) when respective attribute changed in inventoryitem table (again, price). thinking have these 3 classes , map shoppinglistitems directly inventoryitems, i'm unsure of how proceed that. alternatively, possible away shoppinglistitem class entirely , make shoppinglist collection of inventoryitems specified user? input appreciated. in advance!

to redo comments real answer, yes, possible forego shoppinglistitem model in case, long don't need attach data model (e.g. time item added list). link models follows has_and_belongs_to_many association:

class inventoryitem < activerecord::base     belongs_to :item     belongs_to :vendor     has_and_belongs_to_many :shopping_lists end  class shoppinglist < activerecord::base     belongs_to :user     has_and_belongs_to_many :inventory_items end 

this allow assign array of inventory items inventory_items attribute of shopping list, , rails create or delete necessary join records automatically. more information rails guides. note you'll still need join table in schema -- there isn't model associated it. in case, migration might this:

create_table :inventory_items_shopping_lists, id: false |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 

note in order rails auto-detect table, name should combined plural forms of both models in alphabetical order. otherwise need specify table name using join_table option when defining association.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -