1

我在使用 Rails 3.2.1 时遇到问题,嵌套资源一直在抱怨未初始化的常量,我不知道为什么,因为对我来说,似乎我已经完成了与使用不同模型相同的工作。在某些时候,我想我可能在某处使用了保留字,但更改型号名称并没有帮助......

错误:

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>

品牌.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 %>

当我尝试创建一个新系列时,我得到相同的“未初始化常量 Brand::Series”错误,但它指的是“app/controllers/series_controller.rb:21:in `new'”,即这一行“@意甲=@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

4

1 回答 1

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 的单一化方法无法获得“正确”的单数形式series。如果一切都按照您的预期进行,那class_name将是"Serie"(请注意最后的缺失s)。

幸运的是,您可以告诉 rails 为关系使用指定的类名。因此,只需将您的Brand课程更改为此,您就可以了:

class Brand < ActiveRecord::Base
  has_many :series, :class_name => "Serie", :order => "name, id ASC", :dependent => :destroy
end
于 2012-03-24T10:04:54.027 回答