我正在为与汽车维护相关的约会模型创建一个高级搜索/过滤器,其中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中显示生成的过滤器:
<% 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 %>
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?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。