Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with self-referential has_many :through associations in Rails

I was reading about self-referential has_many :through data situations today, because I'm trying to build a Rails application that uses them. I found this example situation on the Internet, and I have a question about it. Let me post this example code from this guy's blog:

create_table :animals do |t|
  t.string :species
end
create_table :hunts do |t|
  t.integer :predator_id
  t.integer :prey_id
  t.integer :capture_percent
end

class Animal < ActiveRecord::Base
  has_many :pursuits,  :foreign_key => 'predator_id',
                       :class_name => 'Hunt',
                       :dependent => :destroy
  has_many :preys,     :through => :pursuits
  has_many :escapes,   :foreign_key => 'prey_id',
                       :class_name => 'Hunt',
                       :dependent => :destroy
  has_many :predators, :through => :escapes
end
class Hunt < ActiveRecord::Base
  belongs_to :predator, :class_name => "Animal"
  belongs_to :prey,     :class_name => "Animal"
end

Let's say I'm building a web page that lists the first animal in its database. Underneath this heading is a list of percentages (capture_percent). Each percentage is referring to an animal that this page's animal hunts, but it doesn't tell you the animal's name, just the percentage. Clicking on any given percentage will then take you to the corresponding animal's page.

This is kind of a difficult question to wrap your head around, I know, but I'm trying to figure it out. Would I have to create a separate table for CapturePercent, maybe?

like image 280
Adam Rezich Avatar asked Dec 13 '08 06:12

Adam Rezich


1 Answers

Would I have to create a separate table for CapturePercent, maybe?

Not at all, there doesn't seem to be anything complicated about this:

<ul>
<% @animal.pursuits.each do |pursuit| %>
  <li><%= link_to "#{pursuit.capture_percent}%", pursuit.prey %></li>
<% end %>
</ul>
like image 147
Gareth Avatar answered Sep 19 '22 15:09

Gareth