Rails Association问题

时间:2010-03-20 04:37:54

标签: ruby-on-rails arrays associations associative-array

我在这种关联方面遇到了麻烦。

我需要获得属于排中士兵的一系列初选。所以,一旦我把所有士兵都排成一排:     @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 %>

***所以没有初选方法,我认为这是因为我试图在数组上调用关联。士兵有一个排,但初选没有,他们只与那个排的士兵有联系。我该怎么做呢?我需要它来返回一组Primaries。提前谢谢!

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

1 个答案:

答案 0 :(得分:0)

你可以穿过士兵:

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

这不是最佳或优雅的。更好的解决方案是:

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

然后你的观点是:

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