【问题标题】:Search a model's reference's/foreign_key's attribute (in rails using SQLite3)搜索模型的引用/foreign_key 的属性(在使用 SQLite3 的 Rails 中)
【发布时间】: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


    【解决方案1】:

    最好的方法是在相关模型中也有一个搜索功能。

    这样你就可以说

    user.search(search)
    

    然后以这种方式取回您的清单。

    【讨论】:

    • 如果我使用 Entry 模型来生成我的列表,有什么办法可以做到这一点?我在原始帖子中添加了一些细节,展示了我如何填充我的表格。
    猜你喜欢
    • 2015-09-14
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 2012-04-17
    相关资源
    最近更新 更多