如何解决未初始化的常量Search :: error-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

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

小六码奴 2019-04-10 15:50:44 978

我正在为与汽车维护相关的约会模型创建一个高级搜索/过滤器,其中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中显示生成的过滤器:

Search Results


<% 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 %>


除了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)
  • 小六码奴
    2019-07-17 23:33:07

    当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?

    0 0
云计算
使用钉钉扫一扫加入圈子
+ 订阅

时时分享云计算技术内容,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

推荐文章