简体   繁体   中英

Belongs_to and backup belongs_to in Rails

This question comes from breaking up a question that was too big.

Users create Events as a Role in a Network . The Events are then connected to both the Role (different Users can occupy that Role when they are hired or fired) as well as the Event . Users that have administrative Roles can access all Events regardless of the Role that created the Event .

It is possible that Role could be destroyed, but the Event will persist as long as the Network exists. (Like if a position is deleted, but they still want the data for retired positions.)

So can the Event both belongs_to a Role and a Network separately? Is that bad rails design? Is there another way to do this? Would I have a special "Retired" role and keep events always tied to a Role and then use belongs_to :network, :through => :role ?

Network.rb

class Network < ActiveRecord::Base
  has_many :roles
  has_many :users, :through => :roles
  has_many :events
end

Role.rb

class Role < ActiveRecord::Base
  belongs_to :user
  belongs_to :network
end

Event.rb - Is this right?

class Event < ActiveRecord::Base
  belongs_to :role  
  belongs to :network
end

In my opinion it's not bad design with your associations (Events belonging to both Role and Network). And I think it's more confusing to have a "retired Role" than have it NULL. But perhaps you should consider having a column status on the Role rather than deleting it. If the status is not eg 1 (if 1 = ok and 2 = inactive as an example) it can't be used anymore, acting as it was deleted.

It's difficult to give an advice when you don't have the whole picture, but, as I said, in my opinion it's no need for a "retired" Role just to be able to change the associations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM