模型中未初始化的常量

时间:2011-08-16 21:09:12

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

我有一个使用Mongoid的非常简单的模型。我已经添加了使用Redcarpet解析MD并存储它。但是在update_attributes期间,它会抛出异常。运行模型并通过rails c运行更新可以正常工作。

class Post
  include Mongoid::Document
  field :contents_markdown
  field :contents

  key :title

  before_create :markdown
  before_save :markdown

  protected
  def markdown
    if self.contents_markdown
      self.contents = Redcarpet.new(self.contents_markdown).to_html.html_safe
    end
  end
end

这是爆炸的控制器。

def update
  @post = Post.find(params[:id])

  respond_to do |format|
    if @post.update_attributes(params[:post])
      format.html { redirect_to @post, notice: 'Post was successfully updated.' }
      format.json { head :ok }
    else
      format.html { render action: "edit" }
      format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
end

这是异常和堆栈跟踪。由于我从模型中删除了东西,因此行号略有偏差。

uninitialized constant Post::Redcarpet

app/models/post.rb:20:in `markdown'
app/controllers/posts_controller.rb:62:in `block in update'
app/controllers/posts_controller.rb:61:in `update'

如果重要,我正在运行MRI 1.9.2-p290和Rails 3.1-rc5。

编辑 - 这一切在运行测试和通过控制台运行时都能正常工作。但是,通过控制器更新/创建模型似乎总是失败。此外,从堆栈跟踪中,您可以看到模型位于标准位置。

2 个答案:

答案 0 :(得分:1)

您可以尝试将Redcarpet.new更改为::Redcarpet.new,这将告诉Ruby查找顶级常量Redcarpet。我认为这可能会解决它,但问题可能更复杂。

答案 1 :(得分:1)

根据您使用require的方式,您可能遗漏了gemRedcarpet声明。

如果在app/models等标准位置定义Rails自动加载器,则通常会捕获这些内容,或者lib/可选。

通常,您可以通过在require类型文件中添加相应的config/initializers/redcarpet.rb语句,或根据需要更改Gemspec来解决此问题。

相关问题