Question

I have orders and items table. I also have a third table called orders_items. Which I learned on creating from the following link (2nd graph) http://www.tutorialspoint.com/ruby-on-rails/rails-models.htm

models/order.rb

class Order < ActiveRecord::Base
 has_and_belongs_to_many :items, through: :item_order
end

models/item.rb

class Item < ActiveRecord::Base
 has_and_belongs_to_many :orders, through: :item_order
end

[orders_items] table has the following:

integer :order_id
integer :item_id

Do I have to create a models/order_item.rb file to add:

belongs_to :order
belongs_to :item

If so what is the correct naming format that it should be? Would the name for the model file [order_item.rb] correct to distinguish which table it refers to?

models/order_item.rb ??

class OrdersItem ??? < ActiveRecord::Base
 belongs_to :order
 belongs_to :item
end
Was it helpful?

Solution

From the API

The join table should not have a primary key or a model associated with it. You must manually generate the join table with a migration such as this

class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
  def change
    create_table :developers_projects, id: false do |t|
      t.integer :developer_id
      t.integer :project_id
    end
  end
end

Specifies a many-to-many relationship with another class. This associates two classes via an intermediate join table. Unless the join table is explicitly specified as an option, it is guessed using the lexical order of the class names. So a join between Developer and Project will give the default join table name of “developers_projects” because “D” precedes “P” alphabetically

In your case the join table name should be items_orders.

OTHER TIPS

Your model must be named OrderItem. And you don't need belongs_to in this class. The file name (order_item.rb) is correct.

I think you need this relationship to fulfill your needs, except if orders is an item too

class Order < ActiveRecord::Base
  has_many :items
end

and

class Item < ActiveRecord::Base
    belongs_to :order
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top