Forum: Ruby on Rails n:through:1 Relation or n:m with another table

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Ee469623eb1b8e6e35d192822b9c4aa2?d=identicon&s=25 Florian Aßmann (Guest)
on 2007-01-22 02:39
(Received via mailing list)
# Hello,

# currently I have 3 tables: users, projects and customers but customers
# soon should become part of users too so I decided to create a relation
# through projects but has_many :through doesn't work in this case,
# because AR generated me a wrong WHERE clause.

## create_projects.rb
create_table "projects", :force => true do |t|
   t.column "title",       :string,                    :null => false
   t.column "description", :text
   t.column "fee",         :integer, :default => 2000, :null => false
   t.column "tax",         :integer, :default => 19,   :null => false
   t.column "client_id",   :integer,                   :null => false
   t.column "agent_id",    :integer,                   :null => false

class User < ActiveRecord::Base
   has_many :clients, :through => :projects

class Project < ActiveRecord::Base
   belongs_to :client, :class_name => 'Customer', :foreign_key
=> :client_id
   belongs_to :agent, :class_name => 'User', :foreign_key => :agent_id

# The definition of an class_name or the relation from User class itself
# seems to baffle AR to build a wrong WHERE clause, although I defined a
# foreign_key in projects relation...
# So I tried to use a n:m relation, which seems to fit better, but I
# get duplicates which I could not get rid off using :uniq => true.

## user.rb
class User < ActiveRecord::Base
   has_and_belongs_to_many :clients,
     :class_name => 'Customer', # Becomes a User in future
     :association_foreign_key => :client_id,
     :foreign_key => :agent_id,
     :join_table => :projects,
     :uniq => true # !! Doesn't seem to work :(

clients = user.clients.uniq # !! Doesn't work too :(

This topic is locked and can not be replied to.