我跟随Railscasts第111集(高级搜索),它在后端工作,但我无法弄清楚我在显示搜索结果时出错了什么
<% @search.listings.each do |listing| %>
<%= render partial: "categories/listing-s" %>
<% end %>
我不会把所有代码都放在她身上,因为它很简单。我有清单模型,显示清单的类别模型和搜索操作的搜索模型。搜索表单位于每个类别的侧栏中
假设我想过滤价格在2000到2400之间的商品。
Started POST "/searches" for 127.0.0.1 at 2016-10-20 21:08:16 +0300
Processing by SearchesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZoKN3mhgmk8ejJE8OKKo+yS7X1R5d7LRzGa9YaIuDVoahH0Fq8iMwclSMVZIej9YwI9i3/8ji+g65A8XRTVhtQ==", "search"=>{"keywords"=>"", "category_id"=>"", "min_price"=>"2000", "max_price"=>"2400"}, "button"=>""}
(0.2ms) BEGIN
SQL (0.5ms) INSERT INTO "searches" ("keywords", "min_price", "max_price", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["keywords", ""], ["min_price", #<BigDecimal:7fbab61ebc98,'0.2E4',9(18)>], ["max_price", #<BigDecimal:7fbab61ebba8,'0.24E4',9(18)>], ["created_at", 2016-10-20 18:08:16 UTC], ["updated_at", 2016-10-20 18:08:16 UTC]]
(2.3ms) COMMIT
Redirected to http://localhost:3000/searches/15
Completed 302 Found in 7ms (ActiveRecord: 3.0ms)
好的,它已经创建并且对我来说很好看。然后我有
Started GET "/searches/15" for 127.0.0.1 at 2016-10-20 21:08:16 +0300
Processing by SearchesController#show as HTML
Parameters: {"id"=>"15"}
Search Load (1.1ms) SELECT "searches".* FROM "searches" WHERE "searches"."id" = $1 LIMIT $2 [["id", 15], ["LIMIT", 1]]
Rendering searches/show.html.erb within layouts/application
.....
Listing Load (0.6ms) SELECT "listings".* FROM "listings" WHERE (price >= '2000.0') AND (price <= '2400.0') ORDER BY created_at DESC
#<Listing:0x007fbab6bea6e0>
#<Listing:0x007fbab6bea500>
#<Listing:0x007fbab6bea3c0>
#<Listing:0x007fbab6bea190>
Rendered searches/show.html.erb within layouts/application (81.0ms)
日志的最后一部分返回和清单模型的集合,这很棒。为什么我仍然看到未定义的方法`每个&#39; for nil:NilClass on&lt;%@ search.listings.each do | listing | %GT; ?
使用searhes_controller中的show动作进行更新
def show
@search = Search.find(params[:id])
end
MODEL
class Search < ApplicationRecord
def listings
@listings ||= find_listings
end
private
def find_listings
listings = Listing.order('created_at DESC')
listings = listings.where("name like ?", "%#{keywords}%") if keywords.present?
listings = listings.where(subcategory_id: category_id) if category_id.present?
listings = listings.where("price >= ?", min_price.to_s) if min_price.present?
listings = listings.where("price <= ?", max_price.to_s) if max_price.present?
listings
puts listings
end
end
**更新2 **
在社区的帮助下,我发现我不应该在模型中使用puts ,因为它返回nil。希望它能帮助您,以防您遇到类似的问题
答案 0 :(得分:2)
Try removing puts listing from the last line, as puts returns nil. so your find_listings
method is returning nil instead of actual listings.