Sunday, January 29, 2006

Creating relations between two models - Active Records

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

belongs_to :category


Open category.rb, and put

has_many :resources



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:

@resource.category.category_name


Assuming we have @category containing a category object, the following will get all resources that belong to that category

@category.resources



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:
<select name="resource[category_id]">\n <% @categories.each do |category| %> \n <option value="<%= category.id %>" \n <%= ' selected' if category.id == resource.category_id %>> \n <%= category.name %> \n </option> <% end %></select>

1 Comments:

At 1:36 PM, Blogger noemi said...

no puedo instalar watir con ruby0.9.4 de forma .gem update --system
hay otra manera?

there is other?

 

Post a Comment

<< Home

eXTReMe Tracker