2013-10-14 81 views
0

我在ROR中有两个模型,一个是Note,另一个是Access。每个Access都有一个注释字段和一个用户字段。在笔记控制器的索引操作中,我想过滤用户拥有的笔记(完成)以及用户可访问的笔记,我将其命名为@accessible_notes。 以下代码为我提供了用户拥有的正确注释,但是我无法获取用户可访问的注释。如何从另一个模型访问模型?

基本上,我需要找到用户参与的所有访问,然后获取相应的注释。我怎样才能做到这一点?

def index 
    @notes = Note.where(user: current_user) 
    @personal_access = Access.where("user_id = ?",current_user.id) 
    @accessible_notes = [] 
    @personal_access.each do |accessible| 
    tnote = Note.find(accessible.note_id) 
    @accessible_notes += tnote if tnote 
    end 
end 

回答

0

如何

@personal_access.each do |accessible| 
    @accessible_notes << accessible.note 
end 
@accessible_notes.flatten! 

有可能是使用Active Record queries一个更快的方法。

而更快的方式是在depa的答案。

2
class User < ActiveRecord::Base 
    has_many :accessible_notes, :through => :accesses, :source => :notes 
end 

@accessible_notes = current_user.accessible_notes 
相关问题