I have a situation where I’m getting a bit stuck.
A Post can have a User (as an author), and a Post can also have many Users (as a post can have other users tagged in it).
In my Post model:
belongs_to :user
has_and_belongs_to_many :users
In my User model:
has_and_belongs_to_many :posts
It works fine generally, but is getting rather stuck when I want to include users on my posts query, and sort the posts by the author’s name.
What should the correct design be? Perhaps replace user_id in Post with author_id?
I can imagine
UserandUsersmessing up your joins. But mind you, as far as my experience this is something that rails does not solve well. Just renaming itauthor(whilst improving the readability/expressing the intention better) will not help, since it will still point to the same tableusers.When doing multiple joins with rails, it is very hard to express your conditions correctly. Rails creates aliases for your tables on the fly, unfortunately I have not find a way to address these aliases in my conditions.
So I think you will either have to resort to a handcrafted sql (which will be fast) or use rails, and get the posts sorted on author-name first, and then retrieve the list of tagged users per post second (which will be slower, but pure ruby).
I would go for the second option first, and optimize to the first if needed.
[UPDATE: add a scope definition]
Personally, I do not favor
default_scopeand instead would propose to define an explicit scopewhich you can then just use in your controller.
Hope this helps.