Unitialized constant in model

青春壹個敷衍的年華 提交于 2019-12-25 02:08:09

问题


I have a very simple model using Mongoid. I've added the use of Redcarpet to parse the MD and store it. However during update_attributes it is throwing an exception. Running the model and running the update through rails c works fine.

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

Here is the controller that blows up.

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

Here is the exception and stacktrace. The line numbers will be slightly off as I have removed stuff from the model.

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'

If it matters, I'm running MRI 1.9.2-p290 and Rails 3.1-rc5.

Edit - This all works fine when running tests and running through the console. However going through the controller to update/create the model seems to always fail. Additionally from the stacktrace, you can see the model is in the standard location.


回答1:


You might be missing a require or a gem declaration depending on how you're using Redcarpet.

The Rails auto-loader will generally catch these if that is defined in a standard location like app/models or, as is optional, lib/.

Usually you can fix this by putting the appropriate require statement in a config/initializers/redcarpet.rb type file, or altering your Gemspec as necessary.




回答2:


You can try changing Redcarpet.newto ::Redcarpet.new which will tell Ruby to look for a top-level constant Redcarpet. I think that will likely fix it, but it's possible that the problem is something more complex.



来源:https://stackoverflow.com/questions/7085053/unitialized-constant-in-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!