Search code examples
ruby-on-railsrubyforeachacts-as-taggable-on

How to modify ActiveRecord_Relation output in Ruby on Rails


I have a Post model combined with gem Acts_as_Taggable_on.

I would like to display all posts with all their tags, but the tags should be sorted by number of their use (number of posts tagged with certain tag).

To do that I looped through ActiveRecord_Relation and did a sort on Tags column:

def index
  temp_posts = Post.all.order('updated_at DESC')
  temp_posts.each_with_index do |temp_post, index|
    temp_posts[index].tags = temp_post.tags.sort_by {|tag| -tag.taggings_count}
  end
  @show = temp_posts.first.tags.sort_by {|tag| -tag.taggings_count} # according to this control output it should work
  @posts = temp_posts
end

When looking through the control output @show, the tags are sorted as required, but they are not saved into the temp_posts variable. The output is thus unsorted.

What can I do to 'save' the changes I made in the loop?


Solution

  • The problem was in the end only with using an invalid variable for saving the sorted tags.

    Acts as Taggable on uses variable tag_list to store the tags associated with the Tag model. Instead I have wrongly used variable tags.

    The full correct version of my code:

    def index
      temp_posts = Post.all.order('updated_at DESC')
      temp_posts.each_with_index do |temp_post, index|
        // CHANGE: temp_posts[index].tags => temp_posts[index].tag_list
        temp_posts[index].tag_list = temp_post.tags.sort_by {|tag| -tag.taggings_count}
      end
      @posts = temp_posts
    end