【发布时间】:2016-02-17 23:06:07
【问题描述】:
我正在尝试对表格执行搜索功能
# my controller EntriesController.rb
def index
@entries = Entry.all
@entries = Entry.search(params[:search])
@entry = current_user.entries.build if logged_in?
end
我能够在我的模型中使用 self.search 方法实现搜索栏
# app/models/entry.rb
class Entry < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
validates :sample, :charge, :need_by, :file_format, :scan_type, presence: true
def self.search(search)
if search
where('created_at LIKE :search OR sample LIKE :search OR
need_by LIKE :search OR scan_type LIKE :search',
search: "%#{search}%")
else
all
end
end
end
到目前为止一切正常,但入口模型通过 user_id 引用用户模型。我希望搜索也能够搜索用户模型。所以我尝试将此添加到entry.rb中的搜索方法
if search
where('user.name LIKE :search', search: "%#{search}%")
end
SQLite3 显然给我一个错误,说“user.name”列不存在。我知道它不存在,但是有什么方法可以访问它而不必使用 Ransack 之类的东西?还是我应该只学习如何使用搜索 gem?
这是完整的例外情况
SQLite3::SQLException: no such column: user.name: SELECT "entries".* FROM "entries" WHERE (user.name LIKE '%asdf%' OR created_at LIKE '%asdf%' OR sample LIKE '%asdf%' OR need_by LIKE '%asdf%' OR scan_type LIKE '%asdf%') AND "entries"."scanned" = ? ORDER BY "entries"."created_at" ASC LIMIT 5 OFFSET 0
目前,我正在使用以下方法填充有问题的表:
<% @entries.each do |entry| %>
<tr>
<td><%= entry.created_at.strftime("%Y %m %d") %></td>
<td><%= entry.user.name %></td>
<td><!-- other entry stuff --></td>
</tr>
<% end %>
TL;DR,我想让 entry.user.name 成为可搜索的词。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 sqlite