has_and_belong_to_many relation

First of all i have a conceptual doubt, I have 2 tables, post and user and both have many to many relation. Ok i do put in both models
Post Model
has_and_belongs_to_many :users
Users Model
has_and_belongs_to_many :posts

after this i’ved create posts_users model with id_user and id_post and a table for that, is this right???

Then another cuestion I want that when a post is created, generate a row in the posts_users table with the id_user and the id_post.

If anyone can help please thank you very much.

Felipe Vergara wrote:

First of all i have a conceptual doubt, I have 2 tables, post and user
and
both have many to many relation. Ok i do put in both models
Post Model
has_and_belongs_to_many :users
Users Model
has_and_belongs_to_many :posts

after this i'ved create posts_users model with id_user and id_post and
a
table for that, is this right???

You don't need the intermediate model if it has no further attributes.
You just need a join table.

create_table :users_posts, :id => false do |t|
  t.integer :user_id
  t.integer :post_id
end

You should probably also create indices and unique constraints to this
table, but that's fairly advanced.

Then another cuestion I want that when a post is created, generate a row
in
the posts_users table with the id_user and the id_post.

This is automatically done for you if you set the model properties,
e.g.:

an_user.posts << a_post
an_user.save

If anyone can help please thank you very much.

Hope that helped,
GG

That does actually need to be posts_users (alphabetic order). You can of course override the name of the join table to be anything you want but there's no reason to if you don't need to.

Fred

thak you very much!!! that helped me a lot i have one last cuestion

where do i put this??
an_user.posts << a_post

an_user.save
in the users model?

in the controller (i guess)