One to Many Association
Greetings Geeks,
A library has_many books. The books all belong to one particular library. Our simple CMS application is gonna make good use of one-to-many associations. Our subject-page relationship is going to be a one-to-many relationship. Each subject has_many pages, and a page belongs_to a subject. Each page also has_many sections, and each section belongs_to a page. Whenever you see belongs_to, remember, that's your tip on where to put the foreign key. We already created the foreign keys for both pages and for sections.
For pages, we had subject ID and we worked on that in the last movie. On this section's table, we already have a foreign key called page IDthat holds its relationship to the page. So we're okay on that point. And also remember that you should always define both sides of the association. Both the has_many and the belongs_to. Once we define these relationships in our model, Rails provides a few methods automatically. This was true with has_one but with has_many, we get more methods. First, we get subject.pages. It's very similar to subject.page that we had before, but now it's plural, and of course, it returns an array of objects to us, all of the pages related to a subject.
If we wanna add a page to that collection, then we use the append operator. That's what we would normally use to append something onto an array, and it looks like <<. That would take a page object and add it to the subject's pages. We can always use the equals operator, but if we do, then we have to define everything that's in the collection. So subject.pages equals exactly these three pages. If we want to remove just a single page from the collection, then we do that with subject.pages.delete and then as an argument, we provide the object for the page that we wanna delete.
We can do this same thing with destroy which will not only remove the association but destroy the page as well. If we wanna remove all pages, then we could just set the equal to an empty array using the equal sign, or you can use clear, and clear will do the same thing. If we wanna know whether we've cleared it, and find out if that array is empty, we can use the empty method, just like you can on a normal array, and if we wanna know specifically how many items are in the collection, we can use the size method.
Thanks,
Maitrey Patel
Comments
Post a Comment