0

I have these models:

class A < ActiveRecord::Base
    has_and_belongs_to_many :Bs
end

class B < ActiveRecord::Base
    has_and_belongs_to_many :As
end


class CreateAs < ActiveRecord::Migration
  def change
    create_table :as do |t|
      t.string :name
      t.timestamps null: false
    end
  end
end

class CreateBs < ActiveRecord::Migration
  def change
    create_table :bs do |t|
      t.string :name
      t.timestamps null: false
    end
  end
end

If table 'as' has the following entries:

  1. "A1"
  2. "A2"
  3. "A3"

and table 'bs' has the following entries:

  1. "B1"
  2. "B2"
  3. "B3"

Does table 'as' have a foreign_key of b and vice-versa?

If yes, then how does internal mapping take place in Rails 4? How it will map? And how can I join and display both these tables?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • Indent your code properly to format the question, it's horrible to read like that. – RichardAE Oct 02 '15 at 13:43
  • 1
    Possible duplicate of [Rails 3 has\_and\_belongs\_to\_many migration](http://stackoverflow.com/questions/6561330/rails-3-has-and-belongs-to-many-migration) – D-side Oct 02 '15 at 13:45
  • I dont how it came on one line. The identation was proper i think at the time of posting. – Akash Gupta Oct 02 '15 at 13:51
  • Welcome to Stack Overflow: "The identation was proper i think at the time of posting." It might be proper in your editor, but SO uses Markdown to provide formatting hints in the content. The "help" and "advanced help" links in the SO editor will show you how to format. Please review those as proper formatting helps us read your posting, which helps you get an answer. – the Tin Man Oct 02 '15 at 19:08

3 Answers3

0

The table does not have the foreign keys as it's a has_and_belongs_to_many relationship - they will be linked via a new join table which you need to create:

rails generate migration CreateJoinTableAB a b
RichardAE
  • 2,945
  • 1
  • 17
  • 20
  • I created that now. create_join_table :as, :bs do |t| t.index : [ a_id, b_id ] ....1 t.index : [ b_id, a_id ] .....2 end Is it ok ? Or only '1' is required? – Akash Gupta Oct 02 '15 at 14:10
0

You will need to create a join table for that. Something like:

class CreateJoinTableAB < ActiveRecord::Migration
  def change
    create_join_table :as, :bs do |t|
      # add some idexes depending on your use case
      # t.index :a_id
      # t.index :b_id
    end
  end
end

Read more about this in the Rails Guide

spickermann
  • 100,941
  • 9
  • 101
  • 131
  • Oh! Okay. Now i made that table. How can i display both ? Or more specifically how can i fetch a particular tuple after joining ? – Akash Gupta Oct 02 '15 at 14:06
0

Look at the Rails Guide for has_and_belongs_to_many. It is all described there. With a nice picture about the database structure.

http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

Meier
  • 3,858
  • 1
  • 17
  • 46