0

Hey I'm just getting back into rails and I've forgotten a lot of the stuff needed to work with some associations.

The Problem:

I have two tables, Customer with fiels id and user_id and User with field id. I want to get an array of Users such that a Customer's user_id is the id of a User. I know how to do this in SQL but forgot how to do this in Ariel.

Edit

So I think I need to explain a little more. I'm taking over an existing project. There's a one-to-one relation between users and customers however only some users have a related customer entity so calling user.customer will return nil most of the time. I need to edit a page that currently lists all users but now I need to list only users that have a customer record.

The relationships have already been created by the previous developer:

class Customer
  belongs_to :user, :class_name => "Refinery::User"
end

Refinery::User.class_eval do
  has_one :customer
end

and I have the following code in my controller:

def index
  # i need to return an array of users, such that the only
  # users in this array are the ones with a non-nil customer.
  @users = Refinery::User.paginate(:page => params[:page])
end

Any help would be great, thanks!

stacker
  • 68,052
  • 28
  • 140
  • 210
aarona
  • 35,986
  • 41
  • 138
  • 186

2 Answers2

1

You can define associations in the two classes, belongs_to in customer and has_many in user.

You will then be able to use Users.find(id).customers etc.

The rails documentation explains this quite well - look at the example of customer and orders.

update following your question update - try

User.where("customer.id IS NOT NULL")

or

@users = Refinery::User.where("customer.id IS NOT NULL").paginate(:page => params[:page])
Ian Kenney
  • 6,376
  • 1
  • 25
  • 44
  • Thanks for your help. The underlying table for customer is 'cust' (i didn't choose this!) so I tried what you said as well as `.where("cust.id IS NOT NULL")` and got this error: `PG::Error: ERROR: missing FROM-clause entry for table "cust"` Should it matter if the class name for `customer` is `Refinery::Akouo::Customer`? – aarona Apr 25 '13 at 09:54
  • Maybe I need to include customers in a join? It looks like this is the SQL output: `SELECT COUNT(*) FROM "refinery_users" WHERE (customer.id IS NOT NULL)` – aarona Apr 25 '13 at 10:00
  • ok this works but I have to add: `.includes(:customer)` just after `User` – aarona Apr 25 '13 at 10:10
0

You don't need any Ariel request for this one.

User :

class User < ActiveRecord::Base
  has_many :customers
end

Customer :

class Customer < ActiveRecord::Base
  belongs_to :user
end

Code :

customer = Customer.find(1)
users = customer.users
Intrepidd
  • 19,772
  • 6
  • 55
  • 63