How do I make many-to-many relationship in Ruby on Rails with has and belongs to many?

2

I have a system table and a table category, a system has many categories and a category has several systems, I wanted to use the has_and_belongs_to_many option of Rails (for being a simple interface and even to learn how to use this feature). But I'm doubtful in the following question, I have to create a migrate that manages a table that stores these relations or type Rails itself will take care of that by putting has_many_and_belong_to: systems and has_many_and_belong_to: Categories?

Has anyone used it, or do you have any suggestions / tips on how to do it?

System controller method

def sistem_params
  params.require(:sistem).permit(:description, :categories)
end

Model Systems

class Sistem < ActiveRecord::Base
  has_and_belongs_to_many :categories

  has_many :versions
end

template Category

class Category < ActiveRecord::Base
  has_and_belongs_to_many :sistems

  has_many :tests
end

Migration of the table linking the templates

class CategoriesAndSistems < ActiveRecord::Migration
  def change
    create_table :categories_sistems do |t|
      t.references :category, :sistem
    end
  end
end
    
asked by anonymous 26.09.2016 / 15:58

1 answer

0

You create a table system_categories

create_table :categorias_sistemas, id: false do |t|
  t.belongs_to :categoria, index: true
  t.belongs_to :sistema, index: true
end

and both in the Category class you will add the

has_and_belongs_to_many :sistemas

And in the System class

has_and_belongs_to_many :categorias

link

I suggest taking care of Portuguese classes because the pluralization of Rails tends to be weird.

    
04.10.2016 / 01:47