我在做搜索。但是我在搜索视图中的each
收到错误
each
工作正常。
但下面是views/search/search_housing.html.erb
,我得到each
:
<tbody>
<% @housings.each do |housing| %>
<tr>
<td><%=link_to "#{housing.title}", housing_path(housing.slug) %></td>
<td><%= housing.category.name %></td>
下面是我的房屋控制器
class HousingsController < ApplicationController
before_action :set_housing, only: [:show, :edit, :update, :destroy]
# GET /housings
# GET /housings.json
def index
@housings = Housing.all.order(created_at: :desc).paginate(page: params[:page], per_page: 10)
end
# GET /housings/1
# GET /housings/1.json
def show
end
# GET /housings/new
def new
@housing = Housing.new
end
# GET /housings/1/edit
def edit
if not @housing.user_email == current_user.email || current_user.email == "codeinflash@gmail.com"
redirect_to @housing
end
end
# POST /housings
# POST /housings.json
def create
@housing = Housing.new(housing_params)
@housing.user_email = current_user.email
respond_to do |format|
if @housing.save
format.html { redirect_to @housing }
flash[:success] = "Housing was successfully created."
else
format.html { render :new }
format.json { render json: @housing.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /housings/1
# PATCH/PUT /housings/1.json
def update
respond_to do |format|
if @housing.update(housing_params)
format.html { redirect_to @housing }
format.json { render :show, status: :ok, location: @housing }
flash[:success] = "Housing was successfully updated."
else
format.html { render :edit }
format.json { render json: @housing.errors, status: :unprocessable_entity }
end
end
end
# DELETE /housings/1
# DELETE /housings/1.json
def destroy
@housing.destroy
respond_to do |format|
format.html { redirect_to housings_url }
format.json { head :no_content }
flash[:alert] = "Housing was successfully destroyed."
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_housing
@housing = Housing.friendly.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def housing_params
params.require(:housing).permit(:title, :type, :description, :location, :user_email, :created_at, :category_id, :slug)
end
end
以下是我的搜索控制器
class SearchController < ApplicationController
def search_housing
@housings = Housing.search((params[:search].present? ? params[:search] : '*')).records.order(created_at: :desc)
# if params[:search].nil?
# @housings = Housing.all.order(created_at: :desc)
# else
# @housings = Housing.search params[:search]
# end
end
end
答案 0 :(得分:1)
此错误来自您的观点:
<% @housings.each do |housing| %>
当你试图访问@housing时,这是零。
尝试放
在控制器中引发异常或binding.pry调试器,并检查查询的结果。
class SearchController < ApplicationController
def search_housing
@housings = Housing.search((params[:search].present? ? params[:search] : '*')).records.order(created_at: :desc)
binding.pry
end
end
我认为您对 Housing.search 的查询返回nil。
要安装binding.pry调试程序,请检查此链接https://github.com/rweng/pry-rails
干杯。
答案 1 :(得分:0)
OH MAY GOD,我找到了方法..
我只是忘了在搜索控制器的end
端...
谢谢你们!