RMcNairn
RMcNairn

Reputation: 491

has many through join table - additional association

I have a table joining two models in a has many through relationship.

Users have many Roles through Authorities

My Authorities table has three columns user_id role_id firm_id

I would like each authority (the join table) to have a one to one relationship with Firms. Is this possible?

--- edit perhaps a little more info would make it clearer.

I have many 'firms'

'users' have many firms through 'follows'

'users' also have a multiple 'roles' through 'authorities'

I am using the cancan gem to restrict the rights of users, so that they can follow any firm, but they can only edit the details of a single firm. This means that I cannot create a direct 1 to 1 association between Users and Firms, as they already have a has many through association - through follows. and Current_user.firms will return all the firms they are following.

As such I would like to store the firm that they have editing rights for in the Authority model, joining Users and Roles.

https://docs.google.com/drawings/d/1CiKsUEdcS6hmKa23xsapWy33NS0Gp1f11a7TgaZbAy0/edit

This should show my table layout - the dotted line is the association i would like to make.

At present my models look like this.

class Firm < ActiveRecord::Base

has_one :authority
has_many :follows, :dependent => :destroy
has_many :users, :through => :follows

class Follow < ActiveRecord::Base
belongs_to :firm
belongs_to :user

 class User < ActiveRecord::Base
 has_many :follows, :dependent => :destroy 
 has_many :firms, :through => :follows
 has_many :roles, :through => :authorities
 has_many :authorities

 class Role < ActiveRecord::Base
 has_many :users, :through => :authorities
 has_many :authorities

class Authority < ActiveRecord::Base
 belongs_to :users
belongs_to :roles
belongs_to :firm

If i can do this how would i go about selecting (in the console I shall work on from that) a specific 'authority' and adding a 'firm'. Further more how would i read this nested attribute?

Thanks in Advance.

Upvotes: 1

Views: 484

Answers (1)

Robin
Robin

Reputation: 21894

I can't see why not. What's your problem exactly?

class Authority < ActiveRecord::Base
    belongs_to :firm
end

class Firm < ActiveRecord::Base
    has_one :authority
end

You should be able to update the firm_id of an Authority like that:

authority = Authority.last
authority.firm = Firm.last # or authority.update_attribute(:firm_id, Firm.last.id)
authority.save

Upvotes: 1

Related Questions