【问题标题】:Sinatra NoMethodErrorSinatra NoMethodError
【发布时间】:2015-10-15 17:17:07
【问题描述】:

我正在尝试在我的 Ruby 应用程序中使用 Haml 文件,但出现以下错误:

NoMethodError at /issues

undefined method `map' for "localhost:27017":String 

index.haml in block in singleton class
9.  -@issues.each do |issue|

app.rb in block in <class:App>
14.     haml :"issues/index"

这是我的 index.haml 文件:

%h1 All Issues

%table.table.table-hover
  %thead
    %tr
      %th Title
      %th Description
      %th Created at
  -@issues.each do |issue|
    %tr
      %td
        %a(href="/issues/#{issue.id}/edit")=issue.name
      %td=issue.description 
      %td=issue.id.generation_time.ago_in_words 
  -unless @issues.any?
    %tfoot
      %tr
        %th
          There are no issues.
          %a.btn.btn-primary(href="/issues/new") Create one 

这里是 app.rb 文件:

require_relative "models/issue"

class App < Sinatra::Base
  enable :sessions
  register Sinatra::Flash

  get "/" do
    "redirect/issues" 
  end   

  get "/issues" do 
    @issues = Issue.all 

    haml :"issues/index"
  end   
end

问题似乎出在我的 -@issues.each 上 |issue|循环,但我确定问题出在 Ruby 语法或 Haml 或其他问题上。我还在 /models 目录中创建了一个 issue.rb 文件,如下所示:

class Issue 
  include Mongoid::Document
  include Mongoid::Timestamps::Updated

  field :name, type: String
  field :description, type: String
end

编辑:我认为我的问题是问题未初始化。我收到一条错误消息:

uninitialized constant Issue::Mongoid (NameError)

【问题讨论】:

    标签: ruby sinatra haml


    【解决方案1】:

    我注意到的第一件事是,hypen 和后面的 Ruby 代码之间没有空格。我不确定这是否真的会对 Haml 的解析方式产生影响,但 all the examples in the Haml reference leave a space,例如

    -@issues.each do |issue|
    

    应该是

    - @issues.each do |issue|
    

    接下来要检查Issues.all 的值,或者通过使用pry 之类的东西进行一些调试,或者只是使用warn 将其输出到控制台,例如

    @issues = Issue.all
    warn @issues
    

    binding.pry
    @issues = Issue.all
    

    index.haml 中的-unless @issues.any? 行也可能受益于更改。 any? 通常用块调用,- if @issues.empty? (IMO) 比 unless 使用较少使用的方法版本更容易理解。

    【讨论】:

    • 在连字符后添加一个空格似乎没有任何作用。我使用了警告 @issues 和 binding.pry,但 issue.rb 文件出现此错误:uninitialized constant Issue::Mongoid (NameError)
    • @KristineRooks 在模型文件中是 require 'mongoid'
    • 你是如何在 sinatra 博客中配置 mongoid 的?您使用了mongoid.yml 文件还是Mongoid.configure 块?由于错误显示调用 map 到“localhost:27017”,即 mongodb 主机,因此可能是连接 mongodb 时的一些配置错误。我猜是 hosts: option given "localhost:27017" ,而不是 ["localhost:27017"]?不过我可能错了。
    • @dreamingblackcat 我认为你必须“@”克里斯汀or a notification isn't sent to them
    • @KristineRooks 请阅读我关于 mongoid 配置的评论。
    猜你喜欢
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    相关资源
    最近更新 更多