Rails - def搜索问题

时间:2017-09-26 13:29:54

标签: ruby-on-rails

好的,我对Rails很新,所以请耐心等待:)

我不确定如何在页面控制器中构建def搜索,以便返回正确的结果(现在结果为空)。 我正在为我的项目调整课程代码。原始课程显示如何按地址搜索房间,而不是通过下拉属性选择。它还按距离而不是价格订购结果。以下是我为我的项目提出的建议:

def search
    # STEP 1
    if params[:search].present? && params[:search].strip != ""
      session[:loc_search] = params[:search]
    end

    # STEP 2
    if session[:loc_search] && session[:loc_search] != ""
      @rooms_type = Room.where(active: true).order(session[:loc_search], order: 'price')
    else
      @rooms_type = Room.where(active: true).all
    end

    # STEP 3
    @search = @rooms_type.ransack(params[:q])
    @rooms = @search.result

    @arrRooms = @rooms.to_a

    end

我很确定def搜索中有几个错误..有人可以帮我解决这个问题吗?

这是我的房间模型属性。

class CreateRooms < ActiveRecord
  def change
    create_table :rooms do |t|
      t.string :type
      t.timestamps
    end
  end
end

主页上的搜索小部件按以下方式构建:

<%= form_tag search_path, method: :get do %>
  <div class="row">
    <div class="col-md-7">
      <%= select_tag :type, options_for_select([['Single', 1], ['Double', 2]]), ,class: "form-control" %>
    </div>

    <div class="col-md-2">
      <%= submit_tag "Search", class: "btn btn-normal btn-block" %>
    </div>
  </div>

<% end %>

搜索页面执行以下操作:

<div class = "row">
  <% @rooms.each do |room| %>
    <div class = "col-md-4">
      <div class = "panel panel-default">
        <div class = "panel-heading preview">
          <% image_tag room.cover_photo (:medium)  %>
        </div>
        <div class = "panel-body">
          <% link_to room.type, room %>
        </div>
      </div>
    </div>
  <% end %>
</div>

谢谢。

基于@crispychicken反馈的更新代码 - 请参阅屏幕截图,在此输入图像说明

enter image description here

1 个答案:

答案 0 :(得分:0)

第一期:您的模型内容错误。它属于迁移。此外,缺少Sub foo() Dim wks As Worksheet Dim wkb As Workbook Dim key As String Dim rowIndex As Integer Dim wksName As Variant Dim LastRow As Integer Set wkb = ThisWorkbook ' for name in input sheet's A1 cell, search the name in all sheets other then input sheet key = wkb.Worksheets("Input").Range("A1").Value ' name to search For Each wks In wkb.Worksheets ' loop through all the sheets If Not wks.Name = "Input" Then ' avoid searching in input sheet itself On Error Resume Next ' to search next sheet when not found in current one wkb.Worksheets("Input").Range("B1").Value = Application.WorksheetFunction.VLookup(key, wks.Range("A:B"), 2, False) End If Next wks End Sub active属性。我认为属性price受到保护。您应该将其重命名为RoomType。

创建迁移:

type

然后执行rails g migration create_rooms room_type:string active:boolean price:integer

第二期:

在您的控制器中,将步骤2中的代码更改为:

rails db:migrate

您必须在文件的任何位置将@rooms_type = Room.where(active: true, room_type: session[:loc_search]).order(:price) 更改为type