如何解决未初始化的常量Search ::错误

时间:2019-04-07 19:47:29

标签: html ruby-on-rails ruby

我正在为与汽车维修相关的约会模型创建一个高级搜索/过滤器,其中schema.rb中的每个表都是:

  create_table "appointments", force: :cascade do |t|
    t.string "VIN"
    t.string "owner_email"
    t.string "date"
    t.string "time"
    t.string "reason"
    t.string "parts_needed"
    t.string "hours_needed"
    t.string "cost"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "searches", force: :cascade do |t|
    t.string "VIN"
    t.string "email"
    t.string "after_date"
    t.string "before_date"
    t.string "time"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

在我的search.rb模型中,我定义了搜索功能:

class Search < ApplicationRecord

    def search_appointments
        appointments = Appointment.all
        # appointments = appointments.where("VIN LIKE ?", VIN) if VIN.present? GIVES ERROR
        appointments = appointments.where("owner_email LIKE ?", email) if email.present?
        appointments = appointments.where("date >= ?", after_date) if after_date.present?
        appointments = appointments.where("date <= ?", before_date) if before_date.present?
        if !time=="Any"
            appointments = appointments.where("time LIKE ?", time) if time.present?
        end

        return appointments
    end
end

然后在我的show.html.erb中显示结果过滤器:

<h2 align="center">Search Results</h2>
</br>


<div class="container-fluid">
    <% if @search.search_appointments.empty? %>
        <p> No Appointments Fit This Search</p>

    <% else %>
        <%= @search.search_appointments.each do |a| %>

        Email: <%= a.owner_email%> </br>
        Date: <%= a.date%> </br>
        Time: <%= a.time%> </br>
        VIN: <%= a.VIN %> </br>

        </br>
        </br>
        </br>
        <% end %>
    <% end %>
    </br>
    <%= link_to 'Return', @search, method: :delete %>
</div>

除了在search.rb模型中的第一个过滤器尝试(注释掉的那一行)之外,其他一切都正常。如果我取消注释该行并运行搜索,则该行将突出显示并且出现错误:

uninitialized constant Search::VIN

我不明白为什么会这样,因为所有其他过滤器都正常工作。谢谢您的任何建议。

搜索控制器:

class SearchesController < ApplicationController

    def new
        @search = Search.new
    end

    def create
        @search = Search.create(search_params)
        redirect_to @search
    end

    def show
        @search = Search.find(params[:id])
    end

    def destroy
        @search = Search.find(params[:id])
        @search.destroy

        redirect_to admin_path
    end

    def search_params
        params.require(:search).permit(:VIN, :email, :after_date, :before_date, :time)
    end
end

我的“新”页面是一种表单,用户可以在其中填写过滤器参数,然后单击提交按钮将其带到显示已过滤约会的显示页面。

1 个答案:

答案 0 :(得分:2)

VIN中引用appointments.where("VIN LIKE ?", VIN)时,ruby正在寻找常量,因为它是大写的。为了访问您的属性,您将需要引用self.VIN或将列名更改为小写(推荐)。

选项1:appointments = appointments.where("VIN LIKE ?", self.VIN) if self.VIN.present?

选项2:

  • VIN列更改为vin
  • appointments = appointments.where("vin LIKE ?", vin) if vin.present?