Acts As View
This plugin allows ActiveRecord to act as view table.
Usage
Let’s consider following table that manages students with two columns “grade” and “deleted”, where “deleted” means logical deletion.
> select * from members;
+----+--------+-------+---------+
| id | name | grade | deleted |
+----+--------+-------+---------+
| 1 | saki | 3 | 0 |
| 2 | miyabi | 2 | 0 |
| 3 | maiha | 2 | 1 |
| 4 | kuma | 1 | 0 |
+----+--------+-------+---------+
{{{
class Member < ActiveRecord::Base; end
}}}
(1) using “acts_as_view” class method
Define view models by “acts_as_view”.
{{{
class ActiveMember < Member
acts_as_view :deleted => false
end
class DeletedMember < Member
acts_as_view :deleted => true
end
class ActiveGrade2Member < Member
acts_as_view :deleted => false, :grade=>2
end
class InheritedActiveGrade2Member < ActiveMember
acts_as_view :grade=>2
end
}}}
We can easily read records as same as using DB view table.
{{{
ActiveMember.find(:all) # => SELECT * FROM members WHERE (( deleted = 'f' ))
DeletedMember.find(:all) # => SELECT * FROM members WHERE (( deleted = 't' ))
ActiveGrade2Member.find(:all) # => SELECT * FROM members WHERE (( deleted = 'f' ) AND ( grade = 2 ))
InheritedActiveGrade2Member.find(:all) # => SELECT * FROM members WHERE (( ( deleted = 'f' ) ) AND ( ( grade = 2 ) ))
}}}
In addition, we can also write records to the view. Note that “grade” and “deleted” columns automatically set.
{{{
ActiveGrade2Member.create(:name=>"chinako")
# => #"chinako", "grade"=>2, "id"=>5, "deleted"=>false}>
}}}
Furthermore, the view constrain also means a restriction to resources. Note that specified “grade” is ignored because the view table forces all members to be active and grade2.
{{{
ActiveGrade2Member.create(:name=>"momoko", :grade=>3)
# => #"momoko", "grade"=>2, "id"=>6, "deleted"=>false}>
}}}
(2) using “create_view” class method
We can dynamically create view model class represented by anonymous (unnamed) class by using “create_view” class method. This is useful when we need dynamical restrictions.
{{{
my_mails = Mail.create_view(:owner_id=>session[:owner_id])
my_mails.find(:all)
# => "SELECT * FROM mails WHERE ( owner_id = ... )
}}}
Cautions
The above restriction feature is wrong with “AR.create!”, because “acts_as_view” is implemented by “with_scope” which is broken about treating “AR.create!”.
Install
This plugin currently depends on “scoped_access” plugin that offers ScopedAccess::MethodScoping class. So we need those both plugins.
http://wota.jp/svn/rails/plugins/branches/stable/acts_as_view/ http://wota.jp/svn/rails/plugins/branches/stable/scoped_access/
- Repository Path: http://wota.jp/svn/rails/plugins/branches/stable/acts_as_view/
- Homepage: http://habtm.com/articles/2006/07/23/acts_as_view