Hard to describe with words, I'll rather show you the code and explain along. Right now I can tell you that I'm writing app with UNIX-like rights system and I've ran into one problem, I don't know how to solve yet. Below are my models with relations.
class Document < ActiveRecord::Base
attr_accessible :name, :rights
belongs_to :folder
validates :folder_id, presence: true
end
class Folder < ActiveRecord::Base
attr_accessible :name, :rights
belongs_to :user
has_many :documents, dependent: :destroy
validates :name, presence: true
validates :user_id, presence: true
end
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation, :user_id
has_many :folders
has_many :group_users
has_many :groups, :through => :group_users
end
class Group < ActiveRecord::Base
attr_accessible :name, :owner
has_many :group_users
has_many :users, :through => :group_users, dependent: :destroy
end
class GroupUser < ActiveRecord::Base
attr_accessible :group_id, :user_id
belongs_to :user
belongs_to :group
end
With my system in mind, every user in group should have access to all folders that the group owner owns(not taking rights in account right now). And this is how I tried to list all folders, user has access to.
In Folders controller
def list_folders
@user_groups = current_user.groups
end
In list_folder view
<table class="table table-striped">
<tr>
<td>Folder name</td>
<td>Documents</td>
<td>Actions</td>
</tr>
<% for group in @user_groups %>
<% user = User.find(group.owner)%>
<% folders = user.folders %>
<% for folder in folders %>
<tr>
<td><%= folder.name %></td>
<td>#</td>
<td><%= link_to 'view', folder_path(folder.id) %></td>
<tr>
<% end%>
<% end %>
</table>
So the problem is with the code right now, if user himself owns a group, his folders get fetched aswell. And I don't want this to happen, because I have other place to watch and edit folders that user owns. Here I want to bring only those that he gets from other groups. I tried to somehow exclude him from query but didnt succeed. Then I tried to remove him from @user_groups array but it also didn't work out the way I wanted. I am open to any suggestions on this problem and also if possible, I'd like to get some hints on how to rewrite the code in view, because iterator(or cycle?) in iterator looks messy for me.