loop
loop

Reputation: 1487

Correct use of has_many_through

I have two models: Orders and Items. This is a many to many relationship, but I'm unsure if HMT is correct

Order model:
-user_id
-transaction_cost
-delivery_time

Item model:
-price
-name

Orders should be able to get all items in the order
Items do not need to be able to get all orders

Upvotes: 0

Views: 33

Answers (1)

fdisk
fdisk

Reputation: 438

The convention on this is to use the names of both models. A good name might be ItemOrders. Has many through is almost certainly a correct choice here.

class Order < ActiveRecord::Base
  has_many :item_orders, dependent: :destroy
  has_many :items, through: :item_orders
end

class Item < ActiveRecord::Base
  has_many :item_orders, dependent: :destroy
  has_many :orders, through: :item_orders
end

class ItemOrder < ActiveRecord::Base
  belongs_to :item
  belongs_to :order
end

Now you just have another ActiveRecord model, and you can add to it as you'd like. It will also be helpful for debugging. You can even use a model/scaffold generator to generate these:

rails g model item_order order:references item:references

This way you get the migrations correct right away. Nothing needs to be altered on your other models except for the above code.

Upvotes: 2

Related Questions