brendon / acts_as_list

An ActiveRecord plugin for managing lists.
http://brendon.github.io/acts_as_list/
MIT License
2.04k stars 355 forks source link

Is positioning limited to explicit belongs_to associations? #321

Closed oyeanuj closed 4 years ago

oyeanuj commented 6 years ago

Hi @brendon, quick question:

Does this plugin work best when there is a foreign key association in the same table (like with a belongs_to associations)?

In my case, I have some complex relationships, like the following:

Posts (of different types like Audio, Video, Image, Text) have a single author and can have many sources (which is tracked in a separate table PostSource". A specific post type needs to be highlighted for each source, but that relationship is inferred through Post, and PostSource

So I am wondering if I can have acts_as_list work where Image can have a position within PostSource without creating new models?

Thank you!

brendon commented 6 years ago

Hi @oyeanuj, acts_as_list doesn't really care about associations. It does care about scopes, but scoped attributes must be on the table that the position column is on. You can overwrite the scoping methods with custom logic but that's advanced usage. I hope that helps. Probably just give it a go and see how you get on :)

brendon commented 4 years ago

Hi @oyeanuj, just to follow this up. You may have been looking to add acts_as_list to your join table. This is possible if you use has_many :through and basically allows you to order the joins. Be sure to set the scope to be one or other of the two foreign keys in the join table.

oyeanuj commented 4 years ago

@brendon Got it, thanks!

oyeanuj commented 2 years ago

@brendon As I thought about alternative solutions to the issue in https://github.com/brendon/acts_as_list/issues/324#issuecomment-1233332821, it brought me to this issue :)

Quick question: For the scope, can I use an attribute from an association model? Say I have Class A which has id and status as attributes. And a Class B which belongs_to Class A. In this case B have an acts_as_list with scope set to A.status field?

brendon commented 2 years ago

As far as I'm aware you can't because of all the shuffling methods. They don't know about your relations so unless you had a default scope that joined the other table then it won't work. Even then it probably won't work as we unscope everything before running the shuffling queries.

oyeanuj commented 2 years ago

I see. Would a case like below be expected to work?

class TodoItem < ApplicationRecord
  belongs_to :author
  belongs_to :todo_list

  acts_as_list scope: [:author_id, :get_todo_list_status]

  def get_todo_list_status
    self.todo_list.status
  end

end
brendon commented 2 years ago

I don't think it would because the scope is exploded into conditions in a .where() call.

https://github.com/brendon/acts_as_list/blob/master/lib/acts_as_list/active_record/acts/scope_method_definer.rb