2012-03-24 78 views
1

我遇到了Rails 3.2.1的問題,嵌套的資源一直在抱怨未初始化的常量,我找不到爲什麼,因爲對我來說,我似乎已經完成了與其他模型一樣,在這種模式下工作。在某些時候,我想我可能會使用一個保留字的地方,但改變模型的名字並沒有幫助...Rails 3.2,嵌套的資源,未初始化的常量

錯誤:

uninitialized constant Brand::Series 
Extracted source (around line #11): 

8: </article> 
9: 
10: 
11: <% @series.each do |serie| %> 
12:  <article class='serie_block'> 
13:   <%= serie.name %> 
14:  </article> 

brand.rb

class Brand < ActiveRecord::Base 
    has_many :series, :order => "name, id ASC", :dependent => :destroy 
end 

serie.rb

class Serie < ActiveRecord::Base 
    belongs_to :brand 
end 

brands_controller.rb

def show 
    @brand = Brand.find(params[:id]) 
    @series = @brand.series 
end 

品牌/ show.html.erb

<% @series.each do |serie| %> 
<article class='serie_block'> 
    <%= serie.name %> 
</article> 
<% end %> 

我得到同樣的 「未初始化的常量品牌::系列」 的錯誤,當我嘗試創建一個新的系列,但是它指的是「app/controllers/series_controller.rb:21:in new」,這是「@serie = @ brand.series.build」這一行。

series_controller.rb

# GET /Series/new 
# GET /Series/new.json 
def new 
    @brand = Brand.find(params[:brand_id]) 
    @serie = @brand.series.build 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @serie } 
    end 
end 

現在奇怪的是,關係似乎工作,Rails的不是抱怨「品牌」不具有「系列」的方法。但是,系列對象的實際創建似乎失敗:s

回答

1

在您的has_many關係Brand中,您使用一個符號,表示您的模型的複數名稱(因爲它應該是)。 Rails現在需要從該符號中找到合適的模型類。要做到這一點,它大致具有以下功能:

relation_name = :series # => :series 
class_name = relation_name.singularize.classify # => "Series" 
class_object = class_name.constantize # in the context of the Brand class: => Brand::Series 

所以罪魁禍首在於Rails的singularize方法不能夠得到series「正確」的單數形式。如果一切按照您的預期完成,class_name應該是"Serie"(注意末尾缺失s)。

幸運的是,你可以告訴rails爲關係使用指定的類名。所以只要改變你的Brand類到這個,你會很好:

class Brand < ActiveRecord::Base 
    has_many :series, :class_name => "Serie", :order => "name, id ASC", :dependent => :destroy 
end 
+0

哇謝謝解決它!現在我也明白爲什麼我的重命名會一直出錯:我只是在'系列'前添加了一些東西(比如'product_series'...我想作爲一個非母語英語的演講者,我只是沒有想到單數「系列」其實是「系列」 – Berggeit 2012-03-24 10:18:49

相關問題