rails 3搜索belongs_to

时间:2013-09-10 12:02:55

标签: ruby-on-rails ruby search belongs-to

我在User模型中有一个搜索方法。但我只能按用户列搜索。用户belongs_to公司模式。

问题:我也希望按user.company.name搜索用户。我怎么能这样做?

user.rb

class User < ActiveRecord::Base
  attr_accessible :email, :name, :password, :password_confirmation, :developer, :admin, :company_id, :boss_id, :company
  belongs_to :company

  def self.search(search)
    if search
      q = "%#{search}%"
      where('name LIKE ? OR 
             company_id LIKE ?',
         q,q)
    else
      scoped
    end
  end

end

index.html.erb

<% provide(:title, 'Users') %>
<h1>Users</h1>

<%= form_tag users_path, :method => 'get' do %>
  <%= hidden_field_tag :direction, params[:direction] %>
  <%= hidden_field_tag :sort, params[:sort] %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

users_controller.rb

class UsersController < ApplicationController
    def index
        @users = User.where(:developer => false, :admin => false).search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 10, :page => params[:page])
    end
end

2 个答案:

答案 0 :(得分:4)

试试这个

def self.search(search)
    if search
      q = "%#{search}%"

      joins(:company).where('users.name LIKE ? OR 
             companies.name LIKE ?',q,q)
    else
      scoped
    end
  end

答案 1 :(得分:2)

@users = User.joins(:company).where(companies: {name: name}, developer: false, admin: false)

现在您只需要将公司名称输入参数即可。