我正在实施一个简单的搜索表单。我想做的是按标题搜索课程。我的课程迁移文件是 lass CreateCourses< ActiveRecord的::迁移
def change
create_table :courses do |t|
t.integer :Course_num
t.string :Title
t.text :Description
t.string :Instructor
t.integer :Instructor_ID
t.date :Start_date
t.date :End_date
t.boolean :Status
t.timestamps null: false
end
add_index :courses, :Course_num, unique: true
end
end
这是我的课程模式:
class Course < ActiveRecord::Base
def self.search(search)
if search
self.where("Title LIKE ?", "%#{search}%")
else
self.all
end
end
end
这是我的控制器的索引部分:
def index
@courses = Course.search(params[:search])
end
这是我的课程索引视图:
<div class="container">
<div class="row col-md-4 col-md-offset-4" style="left: 0%; top: 70px;">
<p id="notice"><%= notice %></p>
<h1>Listing Courses</h1>
<%= form_tag courses_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search], placeholder: "Search Course" %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<table>
<thead>
<tr>
<th>Course num</th>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<% @courses.each do |course| %>
<tr>
<td><%= course.Course_num %></td>
<td><%= course.Title %></td>
<td><%= course.Description %></td>
<td><%= link_to 'Show', course %></td>
<td><%= link_to 'Edit', edit_course_path(course) %></td>
<td><%= link_to 'Destroy', course, :method => :delete, :class=>:destroy, data: { confirm: 'Are you sure?' }%></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Course', new_course_path %>
</div>
</div>
每次我搜索时,它总是告诉我:
PG::UndefinedColumn: ERROR: column "title" does not exist
LINE 1: SELECT "courses".* FROM "courses" WHERE (Title LIKE '%2%')
^
HINT: Perhaps you meant to reference the column "courses.Title".
: SELECT "courses".* FROM "courses" WHERE (Title LIKE '%2%')
我不明白为什么,因为我把&#34; Title&#34;而不是&#34; title&#34;在模型中。我该怎么办?谢谢!
答案 0 :(得分:1)
尝试以下方法:
self.where('"courses.Title" LIKE ?', "%#{search}%")