jeudi 23 juillet 2015

Rails order by association

My goal is to sort the posts by Total amount of votes. As you can see in the controller, at first I sorted the posts by created_at, which worked! However I wanted to change it so it would be sorted by total votes. The votes come from the acts_as_votable gem. Which is associated with Post

Currently this is my posts controller:

    def index
        # @posts = Post.all.order("created_at DESC") <--This works
        @posts = Post.includes(:votes).order("votes_for.size desc")
    end

When I run this I get the following error:Association named 'votes' was not found on Post; perhaps you misspelled it?

My guess is that includes does not work here.

When I open up rails console. To test the association I get the following:

@post = Post.first
@post.votes_for.size

It shows that I currently have 2 votes.

Lastly here is my Post.rb Model

class Post < ActiveRecord::Base
    acts_as_votable
    belongs_to :user
    has_many :comments
    has_attached_file :image, styles: { medium: "700x500>#", small: "350x250>" }
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end

Thanks in advance!!! (I am using psql)

Aucun commentaire:

Enregistrer un commentaire