通过查询搜索时包括父属性

时间:2018-10-21 04:05:50

标签: mysql ruby-on-rails ruby search sqlite

我有一个具有很多求职申请的用户模型。

一切正常,但是当我尝试按用户的名字搜索求职申请时,出现以下错误。

错误

SQLite3::SQLException: no such column: first_name: SELECT  "job_applications"

据我了解,我需要在Job Application查询中包括User属性。

我该怎么做?

查看(工作申请)

<%= form_for :search, :html => {:method => :get, :id => 'search'} do |f| %>
  <%= text_field_tag :terms, params[:terms], :type => 'search' %>
<% end %>

控制器(职位申请)

def index
  @job = Job.find(params[:job_id])
  @job_applications = @job.job_applications.search(params[:terms])
end

模型(工作申请)

def self.search(terms)
  terms ||= ""
  conditions = terms.split(" ").map do |term|
    term = term.strip.gsub("'","''")

    ### I am having an issue here...
    ### how do i include the user attributes in this query
    "first_name like '%#{term}%'"
  end
  where(conditions.join " OR ")
end

1 个答案:

答案 0 :(得分:2)

您必须将job_applications表与users表联接。

# job_applications.rb

def self.search(terms)
    terms ||= ""
    conditions = terms.split(" ").map do |term|
      term = term.strip.gsub("'","''")
      "users.first_name like :term"
    end
    joins(:user).where(conditions.join " OR ")
end

避免将原始用户的输入直接传递到查询中,以避免sql注入。使用rails的内置过滤器或自己进行清理。

def self.search(terms)
    terms ||= ""
    term_args = []
    conditions = terms.split(" ").map do |term|
      term = term.strip.gsub("'","''")
      term_args << "%#{term}%"
      "users.first_name like ?"
    end
    joins(:user).where(conditions.join(' OR '), term_args)
end