Has_many: how does it work?

First of all let me say that I am coming from the php oldschool framework and outdated practice that I am struggling to undo them. When PHP I found NN situations, I just created a new table and had a 1-N relationship to this new table. Example:

tbl_users

tbl_posts

      

Relations:

tbl_users N-N tbl_posts

      

So I just created in a new table and made a 1-N (common has_many) relationship. Example:

tbl_users 1-N tbl_like_posts

tbl_posts 1-N tbl_like_posts

      

I don't know if there was anything equivalent and I didn't use it because I was never charged. But the reality is I looked at has_many: through and couldn't get it in my head. Why can't I do what I did before? What: through specials? What will it make it easier for me I even understand how to use but did not understand why to use.

Sorry if the question was silly, but I'm trying to drop PHP dependencies and learn rails correctly.

+3


source to share


1 answer


You have two options:

1) Let Rails resolve it for you with an association has_and_belongs_to_many

(under the hood, Rails will create a new table to make a many-to-many relationship, but you don't have to deal with it directly);

2) Specify which table you want to use (just like when using PHP) via has_many :through



You can check the docs here: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

Another useful link should be RailsCast: http://railscasts.com/episodes/47-two-many-to-many

+2


source







All Articles