2012-04-26 78 views
0

我正在使用rails has_many通過選項,並不確定如果我在這裏做錯了什麼。我希望球員創造一個賽季,當球員即將創造一個賽季時,它將顯示我在年/新創建的所有賽季的選擇菜單。到目前爲止,這部分工作得很好,但是當一名球員嘗試保存賽季時,rails並不能保存它。我不確定我的關聯是否正確,或者我做錯了什麼?有沒有任何理由爲什麼這不起作用?Rails有很多通過關係

錯誤

No association found for name `season_year'. Has it been defined yet? 

season.rb

class season < ActiveRecord::Base 
belongs_to :player 

has_many :quarters 
has_many :years , :through => :quarters 

attr_accessible :season_year_attributes 
accepts_nested_attributes_for :season_year 
end 

quarter.rb

class Quarter < ActiveRecord::Base 
    belongs_to :player 
    belongs_to :year 
    belongs_to :season 
end 

year.rb

class Year < ActiveRecord::Base 
    attr_accessible :season_year, :season_name 

    has_many :quarters 
    has_many :seasons, :through => :quarters 
end 

player.rb

class player < ActiveRecord::Base 
    has_many :seasons, :through => :quarters 
    has_many :years, :through => :quarters 
end 

_season-form.html.erb

<%= form_for(@season) do |f| %> 
    <div class="field"> 
    <%= f.label :season %> 
    <%= f.text_field :season_name %> 
    </div> 

<%= f.fields_for :years do |year| %> 
<%= select("season", "year_ids", Year.all.collect {|p| [ p.season_year, p.id ] }, { :include_blank => true }) %> 
<% end %> 

<div class="actions"> 
    <%= f.submit %> 
</div> 
<% end %> 

回答

2

根據您的車型,我相信你需要改變這一點:

accepts_nested_attributes_for :season_year 

這樣:

accepts_nested_attributes_for :years 

當你接受嵌套的屬性,它是一個模型,一個不是屬性模型(season_year是年份模型與接受實際模型Year的嵌套屬性的屬性)。

編輯:

在季節模式,我加入year_ids到attr_accessible表達:

attr_accessible :season_year_attributes, :year_ids 

我也改變了本賽季的形式,這樣的選擇列表多年來產量僅爲這個:

<%= select("season", "year_ids", Year.all.collect {|p| [ p.title, p.id ] }, { :include_blank => true }) %> 
+0

感謝沒有注意到,但它仍然不保存我選擇的選擇? – coletrain 2012-04-26 21:00:46

+0

您應該能夠移除<%= f.fields_for:年| do | year | %>,因爲這會循環與選定季節相關的年份,但select()語句正在收集所有年份,無論它們是什麼關聯。回到錯誤...當你保存時,你是否收到錯誤信息? – 2012-04-26 21:27:25

+0

我還在Season模型中爲我的attr_accessible語句添加了「:year_ids」,以便Rails在保存季節時接受year_ids。當我這樣做,它正確保存/更新我的賽季。 – 2012-04-26 21:29:09

1

你不必在你的季節類中的任何season_year,這就是答案。

您是否打算將此作爲一個關聯?

+0

我增加了season_year季節類,它給了我這次只是複數化的同樣的錯誤。 season_year是年份表格的字段名稱。 – coletrain 2012-04-26 20:58:12