0
votes

I am using the acts_as_taggable_on gem: https://github.com/mbleigh/acts-as-taggable-on

and I am trying to show the tags on certain posts but it throws an error:

undefined method `tag_counts_on' for #<Array:0x007fa5d4ac3088>

View:

<% tag_cloud @vote_feed_items.tag_counts_on(:tags).order('count desc').limit(15), %w[a b c] do |tag, css_class| %>
   <%= link_to tag.name, tag_path(tag.name), class: css_class %>
<% end %>

Controller:

@user = User.find(params[:id])
@vote_feed_items = @user.vote_feed

UserModel:

def vote_feed
  Micropost.unscoped.from_microposts_voted_for_by(self)
end

MicropostModel:

def self.from_microposts_voted_for_by(user)
  find_by_sql("select m.* from microposts m
        join (SELECT voteable_id, updated_at FROM votes WHERE voter_id = #{user.id} AND voteable_type = 'Micropost') z on z.voteable_id=m.id
        order by z.updated_at desc")
end

Is find_by_sql returning an array? If so do I need to write this a different way?

1

1 Answers

1
votes

I am not sure, but if what you want is to return a relation you can do this:

def self.from_microposts_voted_for_by(user)
  results = find_by_sql("select m.* from microposts m
        join (SELECT voteable_id, updated_at FROM votes WHERE voter_id = #{user.id} AND voteable_type = 'Micropost') z on z.voteable_id=m.id
        order by z.updated_at desc")
  Micropost.where id: results.map(&:id)
end

find_by_sql returns an array.

With ActiveRecord::Relation

You could build query using relations, I am not sure about your models, I will assume:

class Micropost
  has_many :votes

so your method would be more coherent with Rails inside a scope:

scope(:voted_by, ->(user) do
  joins(:votes).where('votes.voter_id = ?', user.id).order('votes.updated_at desc')
end)

Also you wont hit database eagerly. You would use this scope with something like this:

@microposts = Micropost.voted_by current_user