Relationship has_and_belongs_to_many Rails 4

Asked

Viewed 605 times

1

I have a model of Item has_and_belongs_to_many :generous and a model Gender has_and_belongs_to_many :items, with this I also have a generous item relationship table(id_item, genero_id).

I’m trying to create a new relationship between item and gender in view of the items (show/1), I would first search for all the generos and then with this data I would include this new relationship, but as I do not have a model for the table generos_items and also do not have the controller do not know how to enter this record, which is the best way to proceed?

1 answer

1

One way to do this would be to generate a model (not just the table) for this many-to-many ratio.

This template would contain the id’s of the two related tables. (Tip: Also create a single index for these two columns).

And then you could create a controller for this model to work with.


But if you don’t want to do it the way you create relationships is like this:

@Item.generos = @array_de_generos

So you will have to fetch all genres for the form for the user to add/delete the ones he wants, and via controller you will do something similar to the above line of code to recreate the relations of that model.

In this case there is no method save, the line above recreates the relationships.

View documentation.

See also this question from Stackoverflow-EN.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.