开发者

Correct Associations Ruby on Rails

Can someone help me to correct my associations ?

I have the following models:

开发者_StackOverflow社区
User, Developer, Application, Comments, Rating, Permission

Requirements:

A user can be a Developer or not.
A user can have Default Permissions and Permissions for each application
A user can install multiple Applications
A user can comment and rate multiple Applications
A developer can develop multiple applications
An application can request a list of permissions. 

I already created some associations but I believe its not 100% correct or an easier way to do it exist.

Can someone suggest me a correct way to do it?


You are confusing models with authorization.

You should check out CanCan for role based authorization. For example you don't need your developer model since its just a user with a different role/permissions.

Edit: Changed 'role based authentication' to 'role based authorization'. As the comment below points out the difference between authentication and authorization.


I think this is what you want as far as your model work. You can use a join model to manage your application permissions, and use Rails STI to manage what each type of user can do, whether it's developing or not.

user.rb

class User < ActiveRecord::Base
  has_many :apps
  has_many :comments, :through => :user_comments
  has_many :ratings, :through => :user_ratings
end

comment.rb

class Comment < ActiveRecord::Base
  belongs_to :user
end

rating.rb

class Rating < ActiveRecord::Base
  belongs_to :user
end

user_comment.rb

class UserComment < ActiveRecord::Base
  belongs_to :app
end

user_rating.rb

class UserRating < ActiveRecord::Base
  belongs_to :app
end

normal_user.rb (STI)

class NormalUser < User
end

developer.rb (STI)

class Developer < User
end

app.rb

class App < ActiveRecord::Base
  has_many :permissions, :through => :app_permissions
  has_many :user_comments
  has_many :user_ratings
end

permission.rb

class Permission < ActiveRecord::Base
  belongs_to :app
end

app_permission.rb

class AppPermission < ActiveRecord::Base
end


I agree with @Mark, don't use STI. The better way will be implement as suggested by @Chris Barretto except for STI and use CanCan for role based authentication. The change for User model will be:

class User < ActiveRecord::Base
    has_many :apps
    has_many :comments, :through => :user_comments
    has_many :ratings, :through => :user_ratings
    has_many :roles
end

And there will be another model for Role:

class Role  < ActiveRecord::Base
    has_many :users
end

If you are using gems like Devise for authentication, it will be much easy.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜