styx
styx

Reputation: 87

Traversing Through Multiple Associations (Rails)

I am a little stuck on this one. I would appreciate input.

Overview

I am trying to get the output I require in this friendship model i.e. the files the current user's friends have uploaded.

Models

Like all other friendship models, User is self-referencing as :friend.

class Share < ActiveRecord::Base
    belongs_to :user
    belongs_to :friend, :class_name => "User"
end

This is my Paperclip model:

class Upload < ActiveRecord::Base
    belongs_to :user
    has_attached_file :document
end

This one is generated through Devise:

class User < ActiveRecord::Base
    attr_accessor :login

    has_attached_file :image, :styles => { :medium => "120x120!" }

    has_many :uploads
    has_many :shares
    has_many :friends, :through => :shares
    has_many :inverse_shares, :class_name => "Share", :foreign_key => "friend_id"
    has_many :inverse_friends, :through => :inverse_shares, :source => :user
end

Attempts

The furthest I have gotten into would be the level in which I am able to output the user's friends' :username(s), where @check = current_user in the controller:

<% @check.shares.each |j| %>
        <%= j.friend.username %>
<% end %>

Question

How do I output the :file_name, :file_type, and :document of each of the current user's friends? I intend to have my page look like this:

User's Friend 1 Files

User's Friend 2 Files

Thank you.

Upvotes: 1

Views: 106

Answers (1)

SciPhi
SciPhi

Reputation: 2665

Per the Paperclip documentation :

Paperclip will wrap up to four attributes (all prefixed with that attachment's name, so you can have multiple attachments per model if you wish) and give them a friendly front end. These attributes are:

<attachment>_file_name
<attachment>_file_size
<attachment>_content_type
<attachment>_updated_at

Given that, and with your attachment name of "document" :

<% current_user.shares.each do |share|%>
    <%= share.friend.username %>
    <% share.friend.uploads.each do |upload| %>
        <%= upload.document_file_name %>
        <%= upload.document_content_type %>
    <% end %>
<% end %>

Upvotes: 1

Related Questions