我正在为与汽车维护相关的约会模型创建一个高级搜索/过滤器,其中每个 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
我的“新”页面是一个表单,用户在其中填写过滤器参数,然后单击提交按钮将它们带到列出过滤约会的显示页面。
当您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?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句