So I have a rails app That lets users create lists and put items on that list. As a feature a user can put any one item on multiple lists. Example:
List_1
-item_1
-item_2
List_2
-item_3
-item_2
The relationship side of it all is complete and working fine.
The next step was to let the user arrange the items in their lists. I installed act_as_list and using jQuery sortable got a simple drag and drop working for sorting items. The issue is each item has one position. So if I change item_2’s position to 1 on list_1, item_2’s position is now 1 in every list.
I’m trying to think of a way to store item positions relative to the list. Anyone have any thoughts?
Edit to Add code
List model
class List < ActiveRecord::Base
belongs_to :user
has_many :assignments, dependent: :destroy
has_many :items, through: :assignments, order: 'position'
end
Item model
class Item < ActiveRecord::Base
belongs_to :user
has_many :assignments, dependent: :destroy
has_many :lists, through: :assignments
acts_as_list scope: :list
end
Assignment model
class Assignment < ActiveRecord::Base
belongs_to :item
belongs_to :list
validates_uniqueness_of :item_id, :scope => :list_id
end
So an answered my own question with a little time an effort. I’ve provided an example below for anyone who may run into the issue in the future.
Basically @thedeeno’s answer would have worked fine if I was able to use scopes. In my case the list will be user created and hence scopes are not an option.
Solution:
So my solution was adding a position column to my assignments table (the join table for my has many through)
This way each assignment could now have a list_id and item_id and a position.
Then in my controller I did the following to populate the @items hash
This gave makes @item has ordered by item positions for their respective list position.
Now the last step was updating their position using sortable. To update the correct item’s postion I needed sortable to send the list_id along with each order of the id’s. To get the list_id sent with the post I adding a hidden li with and id of the @list like so
which meant that my params now looked like this
Finally using the skills I had learned from http://railscasts.com/episodes/147-sortable-lists I changed my sort action to the following
That’s it! users can now create any number of lists and item to multiple lists and sort each list independently. Hope this helps someone!