user2205925
user2205925

Reputation: 117

How to access a model from another model?

I have two models in ROR, one which is Note and another one which is Access. Each Access has a Note field and a user field. In my index action of the notes controller I want to filter notes owned by the user (done) as well as notes accessible to the user, which I named @accessible_notes. The following code gives me the correct notes owned by the user, however I cannot get the notes accessible to the user.

Basically, I need to find all the Accesses in which the user is involved and then fetch the corresponding notes. How can I do that?

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

Upvotes: 0

Views: 105

Answers (2)

Marcelo De Polli
Marcelo De Polli

Reputation: 29281

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

@accessible_notes = current_user.accessible_notes

Upvotes: 2

jcm
jcm

Reputation: 1789

How about

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

There might be a faster way using Active Record queries.

And that faster way is in depa's answer.

Upvotes: 0

Related Questions