Search code examples
ruby-on-railsrubyassociationsvote

Rails: List of users who upvoted a model (pin)


So I have a basic rails app where users can upvote a pin - Now I would like to show a list of user who upvoted the pin the view (app/views/pins/show.html.erb)

app/models/user.rb

  has_many :pins    
  has_many :votes, dependent: :destroy
  has_many :upvoted_pins, through: :votes, source: :pin

app/models/pin.rb

has_many :votes, dependent: :destroy
has_many :upvoted_users, through: :votes, source: :user

app/controllers/pins_controller.rb

  def show
    @disable_nav = true
    @pin = Pin.friendly.find(params[:id])
    @pin.upvoted_users

  end

Then i added the code to render who upvoted the pins in app/views/pins/show.html.erb

<ul><li><%= @pin.upvoted_users %></li></ul>

But it shows an association error when I load the page:

#<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_User:0x007fddde186370>

Which is strange because When I inspect @pin.upvoted_users in my rails console I get the users who upvoted the pin correctly.

Any ideas?


Solution

  • This is due to lazy loading.

    To list users, you can use a loop, eg:

    <ul>
      <% @pin.upvoted_users.each do |user| %>
        <li><%= user.name %></li>
      <% end %>
    </ul>