Micro-CMS: Page Content using Model Methods
This article is an enhancement to the Micro-CMS developed in these tutorials, A Micro-CMS in Rails , and Enhancements to Micro-CMS .
What we'll do is add a field to our pages that specifies a Model, Method, and Partial name, delimited by '|'. For example, if you had a model "member" for staff members, you might say "Member|get_list|members_list". The page will then display the "body" field, followed by the list of Members.
First add the modelmethod attribute to the page model:
$ script/generate migration page_add_modelmethod
Edit 003_page_add_modelmethod.rb
def self.up
add_column :pages, :modelmethod, :string
end
def self.down
remove_column :pages, :modelmethod
end
Then,
$ rake db:migrate
Next, lets handle this new model attribute. Edit controllers/pages_controller.rb in def show before the responds_to:
unless @page.modelmethod.nil?
data_model, data_method, @data_partial = @page.modelmethod.split(/\s*\|\s*/)
data_method ||= 'get_list'
@data_partial ||= data_model.downcase.pluralize + '_list'
@data = Object.const_get(data_model).send(data_method)
end
And edit views/pages/show.rhtml, insert this content after the @page.body,
<div>
<%= @page.body %>
<% unless @data.nil? %>
<%= render :partial => @data_partial, :object => @data %>
<% end %>
</div>
OK. Now, a usage example. Since we already have a User model, lets just use that (rather than, say, creating a Member model for staff members as suggested in the beginning). Add to file models/user.rb
def self.get_list
find(:all, :order => "login")
end
Create a partial file view/pages/_users_list.rhtml
<table>
<tr>
<th>User</th>
<th>Email</th>
<th>Joined</th>
</tr>
<% for user in users_list %>
<tr>
<td><%=h user.login %></td>
<td><%=h user.email %></td
<td><%=h user.created_at %></td>
</tr>
<% end %>
</table>
Create a new page named "staff", with body like "<h2>Meet our Staff</h2>", and in the "modelmethod" field add:
User|get_list|users_list
where "User" is the model name, "get_list" is the method that returns a list of users, and "users_list" is the partial (file name pages/_users_list.rhtml).
The last two parts of the field are optional, and per our code, defaults to "get_list" and {model.downcase.pluralized + '_list'}, so in this case it would be sufficient to write
User
Note, you may need to add the modelmethod field to view/pages/new.rhtml and edit.rhml as follows:
<p>
<b>Data Model|Method|Partial</b><br />
<%= f.text_field :modelmethod %>
</p>
(I welcome suggestions how to make this more Rails-way).




Micro-CMS: Page Content using Model Methods
Posted by: Christoph on November 20, 2007 11:27 AM#