Question: I have a search method in `User` model. But I can search only by User columns. User `belongs_to` Company model.

**Question:** I want to search users by `user.company.name` too. How can I do this?

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

```

Answer: 
Try This

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

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

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

```

Now you only need to input your company name into parameters.