【问题标题】:uninitialized constant model1::model2 when trying to retrieve child records尝试检索子记录时未初始化的常量 model1::model2
【发布时间】:2011-05-01 19:04:26
【问题描述】:

我有两种模型,一种用于页面,一种用于作者。

我几乎可以显示哪个作者属于页面,但不断收到错误消息:

uninitialized constant Page::Authors

我在我的页面控制器@pages = @author.pages 中为作者定义了一个方法,但不确定它是否正确。听到是我的控制器代码。

class PagesController < ApplicationController
  def index
    @pages = Page.find(:all, :order => 'created_at DESC')
  end

  def show
    @page = Page.find(params[:id])
  end

  def new
    @page = Page.new
  end

  def edit
    @page = Page.find(params[:id])
  end

  def create
    @page = Page.new(params[:page])

      if @page.save
          redirect_to(@page, :notice => 'Page was successfully created.')
      else
          render :action => "new"
      end
  end

  def update
    @page = Page.find(params[:id])

      if @page.update_attributes(params[:page])
        redirect_to(@page, :notice => 'Page was successfully updated.')
      else
        render :action => "edit"
      end
  end

  def destroy
    @page = Page.find(params[:id])
    @page.destroy
  end

  def author
   @pages = @author.pages
  end
end

这是我的作者控制器:

class AuthorsController < ApplicationController
  def index
    @authors = Author.find(:all, :order => 'created_at DESC')
  end

  def show
    @author = Author.find(params[:id])
  end

  def new
    @author = Author.new
  end

  def edit
    @author = Author.find(params[:id])
  end

  def create
    @author = Author.new(params[:author])

      if @author.save
        redirect_to(@author, :notice => 'Author was successfully created.') 
      else
        render :action => "new" 
    end
  end

  def update
    @author = Author.find(params[:id])

      if @author.update_attributes(params[:author])
       redirect_to(@author, :notice => 'Author was successfully updated.') 
      else
        render :action => "edit" 
    end
  end

  def destroy
    @author = Author.find(params[:id])
    @author.destroy
  end

  def author_id
    @author = @pages.author
  end
end

我只想显示谁创建了这些页面,我正在使用表单中的选择来获取已经输入数据库的作者。当您创建一个新页面时,选择列表被选中并输入内容,然后当您显示新页面或显示模板时,即发生错误。

在我的模型中,我说过belongs_to :author 和has_many :pages。

我很接近。

任何想法都会很棒。谢谢

【问题讨论】:

  • 请注意,&lt;code&gt; 在 StackOverflow 上不起作用。而是缩进四个空格。

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

这里缺少的是堆栈跟踪,它显示了相关行的执行位置。引用Authors 类而不是实际的Author 的错误是很常见的,最终会出现这样的错误。以这种方式,您粘贴的内容似乎没有任何问题。

如果 Author has_many :pagesPage belongs_to :author 那么这应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多