2010-03-20 160 views
1

我遇到了這個問題。導軌協會問題

我需要得到一排屬於士兵的初選陣列。所以,一旦我得到所有的士兵在一個排: @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 

回答

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

非常感謝,那排協會應該是真的很明顯我。 – looloobs 2010-03-23 05:23:23