Browse the Ruby on Rails Community.

You are here: Browse Railsplugins Acts As View

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”)
  1. => #<activegrade2member:0xb75c35c0>”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)
  1. => #<activegrade2member:0xb75bdbac>”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)
  1. => “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/

Author

Maiha <anna>

NOTE: This description has been extracted from the Plugin README and so the formatting may need updating to make browser friendly

Users


See all details


Membership

+ Join this railsplugin

Record Maintainer

'None'