【问题标题】:How to search for all posts containing keyword using Sinatra and Datamapper?如何使用 Sinatra 和 Datamapper 搜索包含关键字的所有帖子?
【发布时间】:2019-09-22 14:13:37
【问题描述】:

我对全栈开发相当陌生,我正在尝试使用一个简单的搜索表单。该网页应该将用户重定向到包含包含关键字的所有视频列表的页面。每当我输入一个存在的标题时,我都会在 /posts/:title/search 处得到 :NoMethodError

我尝试过使用查询但失败了。

这是我的 app.rb。我查询所有包含 :title 的视频。

get "/posts/:title/search" do
    # authenticate!
    @results = Video.all(title: params[:title])

    if @results
        erb :search_success
    else
        flash[:error] = "Video not found."
        erb :search_success
    end

end

这是 search_success.erb,我想在其中获得包含标题中关键字的视频列表。

<div class="container">
    <% @results.each do |r| %>
        <h1><%= r.title %></h1>
    <% end %>
</div>

这是搜索表单所在的 navigation.erb。

<form action="/posts/:title/search" method="get">
        <input type="text" type="text" placeholder="Search" aria-label="Search">
        <button type="submit">Search</button>
  </form>

【问题讨论】:

  • NoMethodError 说明了什么?它来自哪条线路?
  • 它来自 search_success.erb 中的第 2 行。在单例类中阻塞。
  • nomethoderror 是怎么说的?每个 nilclass 的未定义方法?
  • 是的,没错。
  • 鉴于您分享的信息,我不明白这怎么可能。 DataMapper 的all 方法总是返回一个数组,从不为零。请再次检查您的代码和错误是否与您共享的完全相同。此外,您可以通过使用像 pry 这样的调试器来节省数小时的头痛。在导致错误的行之前放置一个断点,看看发生了什么。

标签: html ruby forms sinatra datamapper


【解决方案1】:

尝试改变

@results = Video.all(title: params[:title])

@results = Video.all(:title.like => "%#{params[:title])}%")

获得不需要完全匹配的答案(即匹配大小写等)

同样在您的搜索表单中,您有两个 type 属性。您应该将其中一个更改为

name="title"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 2014-08-03
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多