开发者

Relation/Sort not working in rails controller?

开发者 https://www.devze.com 2022-12-31 18:45 出处:网络
I have the following relation in my rails app: genre - has man开发者_如何学Cy - authors authors - belong to genre and has many books

I have the following relation in my rails app:

genre - has man开发者_如何学Cy - authors

authors - belong to genre and has many books

books - belongs to authors and belongs to users

(users can add books to the db)

in my controller I have:

@books=current_user.books(:include => [:author => :genre], :order => 'created_at DESC')

While I am able to use the @books variable in my views - nothing is done correctly (i.e. its not showing me only books added by that user, and its not descending by created_at)...

any ideas?

--

Also I'm using clearance for the user auth, so current_user without the @ in the controller seems to work fine

Actually, I think the relation is working, only the sort might not be working...


Which created_at do you want to sort on? When you're engaging a join, it's usually safer to be specific:

@books = current_user.books(..., :order => 'books.created_at DESC')

The other thing you can do is sort it in the client which may be faster than having the RDBMS do it if you're not paginating:

@books = current_user.books(...).sort_by(&:created_at).reverse

If you're paginating these results you will need to sort in the query, there's no way around it.

0

精彩评论

暂无评论...
验证码 换一张
取 消