开发者社区> 问答> 正文

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

我正在为与汽车维护相关的约会模型创建一个高级搜索/过滤器,其中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
我的“新”页面是用户填写过滤器参数,然后单击“提交”按钮将其带到列出已过滤约会的显示页面的表单。

展开
收起
小六码奴 2019-04-10 15:50:44 3071 0
1 条回答
写回答
取消 提交回答
  • 当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?

    2019-07-17 23:33:07
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多