【问题标题】:Show action caused Mongoid Criteria error显示操作导致 Mongoid Criteria 错误
【发布时间】:2013-07-10 11:20:13
【问题描述】:

我只是试图通过事件的索引页面访问显示页面,但我不断收到此 mongoid 错误-

Mongoid::Errors::DocumentNotFound at /events/%23%3CMongoid::Criteria:0x007f8ac1da9578%3E

Summary: When calling Event.find with an id or array of ids, each parameter must match a document in the database or this error will be raised. The search was for the id(s): # ... (1 total) and the following ids were not found: #. Resolution: Search for an id that is in the database or set the Mongoid.raise_not_found_error configuration option to false, which will cause a nil to be returned instead of raising this error when searching for a single id, or only the matched documents when searching for multiples.

控制器

  def index
    @event = Event.all
  end

  def show
    @event = Event.find(params[:id])
  end

路线

  resources :events do
    resources :leads, only: [:new, :create]
    resources :registrations, only: [:new, :create]
  end

索引视图

<ul>
  <% @event.each do |e|  %>
  <li><%= link_to e.title, event_path(@event) %></li>
  <% end %>
</ul>

【问题讨论】:

    标签: ruby-on-rails mongodb ruby-on-rails-3.2 mongoid


    【解决方案1】:

    试试这个

    <%= link_to e.title, event_path(e) %>
    

    您必须为每个events 调用link_to 方法,该方法可通过@event.each do |e| 调用中的e 变量访问。

    另外,我建议将@event 重命名为@events,因为它包含多个Event。所以在你的控制器中:

    def index
      @events = Event.all
    end
    

    在你看来:

    <ul>
      <% @events.each do |e|  %>
        <li><%= link_to e.title, event_path(e) %></li>
      <% end %>
    </ul>
    

    【讨论】:

    • 我正在使用 mongoid (3.0.23),以上都给了我未定义的 id 方法。有什么想法吗?
    • 最后一个问题...我有一个 slug 字段,然后在模型中将 to_params 方法定义为 slug 然后在显示控制器中我有 @event = Event.find_by_slug(params[:id] )。
    • 你有什么问题?无论如何,我建议在新线程中询问它;)
    • 谢谢皮埃尔,我开始了一个新线程并得到了答案@event = Event.find_by(slug: params[id]) :)
    猜你喜欢
    • 1970-01-01
    • 2013-10-08
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 2012-12-18
    相关资源
    最近更新 更多