开发者

ruby on rails global method

开发者 https://www.devze.com 2023-03-07 12:32 出处:网络
I have a user controller which consists of a method named listfolders(). class UserController < ApplicationController

I have a user controller which consists of a method named listfolders().

class UserController < ApplicationController

 def myaccount()

    userId = session[:id]

    @listfolders = UsersFolders.listfolders(userId)

    @users = User.listusers()


  end
end

In the views I have and I'm able to fetch the folders:

开发者_高级运维
<% @listfolders.each do |userfolder| %>
<tr>
<td><a href="#" target="cstr"><b><%= userfolder.foldername %></b></a></td>
</tr>
<% end %>

PROBLEM: I want to display the folders in all pages like compose,drafs,trash etc ... instead of just for the action.

How can I do it ?


The basic, standard way to do this would be in a helper.

module ApplicationHelper
  def listfolders(user_id)
    lf = UsersFolders.listfolders(user_id)
    render 'users_folders/listfolders', :listfolders => lf
  end
end

then in app/views/users_folders/_listfolders.html.erb

<% listfolders.each do |userfolder| %>
<tr>
  <td><a href="#" target="cstr"><b><%= userfolder.foldername %></b></a></td>
</tr>
<% end %>

calling it is as easy as:

<% listfolders(session[:id]) %>


If I understand everything right you need some :before_filter in your controller to initialize @listfolders and @users variables


You can easily move the code to load the folder + the partial template to a cell component and then call that cell from any view.

Check this: http://cells.rubyforge.org/

It will work just like the render :partial calls but will add a controller like process that should load the user folders and then will create the partial to be rendered.

The other approach that should work is to have a method on the application_controller to load the folders. Then add a before_filter calling that method to every action that should render the folders. Finally you can create a shared partial to be rendered on each of the views that should be showing that.

Note: The method to load the folders can be defined in a more specific controller if you will only show the folders on actions from the same controller of for a child controller.

0

精彩评论

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