Tuesday, 12 September 2017

HOW TO GET THE VALUES FROM JOIN TABLES:

You have to create two tables .

For example i take customer and product tables.

Consider you need to know about the product which is is particular customer First of all you need to create the rails app...

rails new jointable -d mysql

The above code will create the rails app with the mysql database...

The you need to create the models and join tables ☺

For model creation:
 1. rails g model customer name:string mail:string
 2. rails g model Product name:string





For the Join table :
1. rails g model Join
   

in db file you can create the migration data:

class CreateJoins < ActiveRecord::Migration[5.1]
def change
create_table :joins do |t|
t.references :customer
t.references :product
t.timestamps
end
end
end


Then you have to create  the migration :
   For the migration :
         rake db:migrate
   If you face any Problem :
         just run this : rake db:drop db:create db:migrate

Then you have to create the assosiation for Join table :


class Customer < ApplicationRecord
has_many :joins
has_many :products , through: :joins
end

class Join < ApplicationRecord
belongs_to :customer
belongs_to :product
end

class Product < ApplicationRecord
has_many :joins
has_many :customers , through: :joins
end

These Assosiation You have to create ...

Then open the rails console see the result how it comes...

In the rails console:


Thankyou friends ...

No comments:

Post a Comment