开发者

Rails Association Problem

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


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 %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜