开发者

Rails + simple role system through associative table

So I have the Ninja model which has many Hovercrafts through ninja_hovercrafts (which stores the ninja_id and the hovercraft_id).

It is of my understanding that this kind o开发者_开发问答f arrangement should be set in a way that the associative table stores only enough information to bind two different classes.

But I'd like to use the associative table to work as a very streamlined authorization hub on my application. So i'd also like this table to inform my system if this binding makes the ninja the pilot or co-pilot of a given hovercraft, through a "role" field in the table.

My questions are:

  1. Is this ugly?

  2. Is this normal?

  3. Are there methods built into rails that would help me to automagically create Ninjas and Hovercrafts associations WITH the role? For exemple, could I have a nested form to create both ninjas and hcs in a way that the role field in ninjas_hovercrafts would be also filled?

  4. If managing my application roles this way isn't a good idea, whats the non-resource heavy alternative (my app is being designed trying to avoid scalability problems such as excessive joins, includes, etc)

thank you


This might not answer you question completely, but if you are only going to have two roles for hovercrafts I would instead set up the associations like this

class Hovercraft < ActiveRecord::Base
  belongs_to :pilot, :class_name => 'Ninja', :foreign_key => 'pilot_id'
  belongs_to :copilot, :class_name => 'Ninja', :foreign_key => 'copilot_id'
end

class Ninja < ActiveRecord::Base
  has_many :pilotings, :class_name => 'Hovercraft', :foreign_key => 'pilot_id'
  has_many :copilotings, :class_name => 'Hovercraft', :foreign_key => 'copilot_id'
end

Now if you have more roles than that, or if you need more flexibility you can use a third model to link them together.

class Hovercraft < ActiveRecord::Base
  has_many :hovercraft_roles
  has_many :ninjas, :through => :hovercraft_roles
end

class HovercraftRole < ActiveRecord::Base
  belongs_to :hovercraft
  belongs_to :ninja
end

class Ninja < ActiveRecord::Base
  has_many :hovercraft_roles
  has_many :hovercrafts, :through => :hovercraft_roles
end

With a role attribute in HovercraftRole model to indicated if it is a 'pilot' or 'copilot'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜