2
I have a table system 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 relation and even to learn how to use this resource). But I am doubtful on the following question, I have to create a migrate that manages a table that stores these relations or type Rails itself takes care of it, by placing the has_many_and_belong_to :systems and has_many_and_belong_to :categories?
Has anyone used, or has any suggestion/tip on how to do?
System controller method
def sistem_params
params.require(:sistem).permit(:description, :categories)
end
Modelo Sistemas
class Sistem < ActiveRecord::Base
has_and_belongs_to_many :categories
has_many :versions
end
model Category
class Category < ActiveRecord::Base
has_and_belongs_to_many :sistems
has_many :tests
end
Table migration connecting models
class CategoriesAndSistems < ActiveRecord::Migration
def change
create_table :categories_sistems do |t|
t.references :category, :sistem
end
end
end
I don’t have time now to answer, but yes, migration has to be done when using
has_many_and_belongs_to
. You can see this better here: http://railscasts.com/episodes/47-two-many-to-many– Gabriel Katakura
I was able to create the migrate, the table, and in the console associate system with category, but I still could not do it in the controller and in the view. In the system create/Edit view I want to be able to select in a select multiple the categories it has, and when saving it creates the association, currently by the console it lets associate more than once a category for a system. I am also having problem in the system parameters, I tried to add categoriano (controler), tried nested Attributes and is not working it does not let receive the categories I am trying to select in the form
– André Gava
How are you sending this information to the back end? Put models/migrations with the relationship parts so I can better understand the problem.
– Gabriel Katakura
I added the codes to the description of the question @Gabrielkatakura, need some other part?
– André Gava
Have you tried
category_ids
(passing only an array of Ids) instead ofcategories
?– Gabriel Katakura
post schema.db after migrate for us to see please
– iGallina