Read a join table in ruby on rails

0

As I can read (find, take) a join table created from the contact and group tables, in the migration the join table ContactGroup was created, but I do not see it in the model.

Attachment migration of contact table, group and contact group.

class CreateContactos < ActiveRecord::Migration[5.1]
  def change
    create_table :contactos do |t|
      t.string :nombre
      t.string :numero
      t.string :archivo, default: "** cargado en linea **"

      t.timestamps
    end
  end
end

...

class CreateGrupos < ActiveRecord::Migration[5.1]
  def change
    create_table :grupos do |t|
      t.string :nombre

      t.timestamps
    end
  end
end

...

class CreateJoinTableGrupoContacto < ActiveRecord::Migration[5.1]
  def change
    create_join_table :grupos, :contactos do |t|
      # t.index [:grupo_id, :contacto_id]
      # t.index [:contacto_id, :grupo_id]
    end
  end
end

My versions of ruby and RoR are respectively:

ruby -v

ruby 2.3.3p222 (2016-11-21 revision 56859) [i386-mingw32]

rails -v

Rails 5.1.3

to clone and execute it:

git clone link

cd Contacts and Groups

rails db: migrate

rails s

    
asked by rrg1459 04.09.2017 в 00:44
source

1 answer

0

You can generate your model, simply create the file app / models / groups_contact.rb :

class GruposContacto < ApplicationRecord
end

And you can read it using the find_by 1 or where method, for example:

GruposContacto.find_by(grupo_id: 1)
GruposContacto.where(grupo_id: 1)

The difference is that find_by returns the first record it finds with the given condition, while where returns all that meet that condition.

Both methods accept more than one attribute, so you could do the following:

GruposContacto.find_by(grupo_id: 1, contacto_id: 2)

1 You will not be able to use find since it does not have a column id .

    
answered by 04.09.2017 / 01:12
source