views:

36

answers:

1

I am having trouble with this association.

I need to get an array of the primaries that belong to the soldiers in a platoon. So once I get all the soldiers in a platoon: @company = Company.find_by_id(1) @platoons = @company.platoons

<% @platoons.each do |p| %>
  <%= p.soldiers.primaries.find(:all,:conditions => ["relationship = ? AND contacted = ?", 'Spouse', 'Yes'])) %>
<% end %>

* So there is no method for primaries, I assume this is because I am trying to call an association on an array. Soldiers have a platoon_id but primaries do not, they only have the association to soldiers in that platoon. How do I do this? I need it to return an array of Primaries. Thanks in advance!

class Soldier < ActiveRecord::Base
  belongs_to :company
  belongs_to :platoon
  has_many :primaries, :dependent => :destroy
end


class Platoon < ActiveRecord::Base
  belongs_to :company
  belongs_to :battalion
  has_many :soldiers
end

class Primary < ActiveRecord::Base
  belongs_to :soldier
  belongs_to :company
end
A: 

You could loop through the soldiers:

<% @platoons.each do |platoon| %>
  <% p.soldiers.each do |soldier| %>
    <%= soldier.primaries.find(:all,:conditions => ["relationship = ? AND contacted = ?", 'Spouse', 'Yes'])) %>
   <% end %>
<% end %>

That's not optimal or elegant. A better solution would be:

class Platoon < ActiveRecord::Base
  belongs_to :company
  belongs_to :battalion
  has_many :soldiers
  has_many :primaries, :through => :soldiers
end

Then your view would be:

<% @platoons.each do |platoon| %>
  <%= platoon.primaries.find(:all,:conditions => ["relationship = ? AND contacted = ?", 'Spouse', 'Yes'])) %>
<% end %>
jrallison
Thanks a lot, that platoon association should have been really obvious to me.
looloobs