Search code examples
ruby-on-railsassociationsrelational

two resources with two different relationships in rails


I am new to rails, and have a situation that I can't quite get my head around.

Lets say I have two resources, users and widgets.

Users can use widgets, but widgets are also user created, and should be owned by the user that created them. There needs to be a user uses widget, and a user owns widget. Is the following what I am looking for?

Class User < ActiveRecord::Base
  has_many :uses
  has_many :widgets, :through => :uses
  has_many :owns
  has_many :widgets, :through => :owns
end

Class Widget < ActiveRecord::Base
  has_one :own
  has_many :uses
  has_many :users, :through => :uses
end

Class Use < ActiveRecord::Base
  belongs_to :user
  belongs_to :widget
end

Class Own < ActiveRecord::Base
  belongs_to :user
  belongs_to :widget
end

Solution

  • I would do it slightly different.

    Class User < ActiveRecord::Base
      has_many :uses
      has_many :widgets, :through => :uses
      has_many :owned_widgets, :class_name => "Widget"
    end
    
    Class Widget < ActiveRecord::Base
      belongs_to :owner, :class_name => "User"
      has_many :uses
      has_many :users, :through => :uses
    end
    
    Class Use < ActiveRecord::Base
      belongs_to :user
      belongs_to :widget
    end
    

    I changed the names a bit, you had a name conflict on widget, you cannot have two associations with the same name. I also removed the has_one and just set an owner which will have a foreign_key of owner_id with the class set to User. Other than that, you set the many-to-many relationship up nicely.