Skip to content

Tutorial: linking object and subject with HMT

EnriqueVidal edited this page Sep 27, 2012 · 1 revision

Without database views:

This is the simplest way to achieve this and it will work on rails 3+: http://coderwall.com/p/752fjw

With database views:

#Just one migration
class CreateRolesViews < ActiveRecord::Migration
  def self.up
    execute('CREATE VIEW roles_views AS SELECT roles.id, roles_users.user_id, roles.name, roles.authorizable_type, roles.authorizable_id FROM roles INNER JOIN roles_users on roles.id = roles_users.role_id')
  end
  def self.down
    execute('DROP VIEW roles_views')
  end
end
#app/models/roles_views.rb
class RolesView < ActiveRecord::Base
  belongs_to :user
  belongs_to :authorizable, :polymorphic => true
end
#app/models/user.rb
class User < ActiveRecord::Base
  acts_as_authorization_subject
  has_many :roles_views
  has_many :posts, :through => :roles_views, :source => :authorizable, :source_type => 'Post'
end
#app/models/post.rb
class Post < ActiveRecord::Base
  acts_as_authorization_object
  has_many :roles_views, :as => :authorizable
  has_many :users, :through => :roles_views
end

Now we can do something like that:

User.first.posts
User.first.posts.all :conditions => "roles_views.name = 'owner'"
Post.all :include => :users

Etc...