代码之家  ›  专栏  ›  技术社区  ›  Serge Pedroza

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

  •  1
  • Serge Pedroza  · 技术社区  · 6 年前

    我有一个用户模型,它有许多作业应用程序。

    一切都很好,但是当我尝试用用户的名字搜索工作申请时,我会得到下面的错误。

    误差

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

    根据我的理解,我需要在作业应用程序查询中包含用户属性。

    我怎样才能做到这一点?

    视图 (工作申请)

    <%= 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 回复  |  直到 6 年前
        1
  •  2
  •   neume    6 年前

    你必须加入 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
    
    推荐文章