This post will show you how you can create relations between two tables / models / Active Records.
For example, I have a resources table and a categories table and I would like to make sure that when adding another resource I can choose / select a category.
Vice versa, I would like to be able to get the resources that belong to a category.
We'll assume all the tables we need exist with the proper field names.
For my application:
A portal has many categories
A category has many resources
A tag has many resources
I will be creating some relations here, but you should get the idea.
Open resource.rb (the model which will have categories) and add
Open category.rb, and put
We just told Rails that a resource belongs to a single category and that a category can have many resources.
So what do these declarations do? After putting these declarations, we can use:
Assuming we have @category containing a category object, the following will get all resources that belong to that category
In resource_controller.rb, we can now change our edit and new functions and add the following so we can have a collection available when we are adding or editing resources.
@categories = Category.find_all
Then in our edit.rhtml and new.rhtml we can put something like: