I'm setting up a collaborative writing platform. A user can have sets of items where any item can be in any set and belong to any user. This leads to a few problems though.
These are my model relationships:
class Association < ActiveRecord::Base
belongs_to :user
belongs_to :set
belongs_to :item
end
class Set < ActiveRecord::Base
has_many :associations
has_many :users, through: :associations
has_many :items, through: :associations
end
class Item < ActiveRecord::Base
has_many :associations
has_many :users, through: :associations
has_many :sets, through: :associations
end
I can't figure out the "rails way" of handling this correctly.
Problem 1:
When creating a new item, only the set/item association is stored and not the user:
class ItemsController < ApplicationController
def create
@set = current_user.sets.find(params[:set_id])
@set.where(title: params[:item][:title]).first_or_create!
end
end
*UPDATE*
To fix problem 1, the best I could figure out was to do the following:
@set = current_user.sets.find(params[:set_id])
@item = Item.where(name: params[:item][:title]).first_or_create!
Association.where(item_id: @item.id, set_id: @set.id, user_id: current_user.id).first_or_create!
Feels very wrong though!
Problem 2:
Assuming the associations table is populated correctly from problem 1, the following controller will return all items owned by the set but disregard user ownership:
class SetsController < ApplicationController
def index
@sets = current_user.sets.includes(:items)
end
end
*UPDATE*
Still no luck finding an answer on this. To explain the problem a bit better:
The following will return only sets that belong to the current user
@sets = current_user.sets.all
However, the following will return only the user's sets but will include ALL of the items for the sets even if they don't belong to the current user. In other words, the user scope is dropped.
@sets = current_user.sets.includes(:items)
I've been trying to solve this all day and can't seem to find a lead
Your first problem is making sure your instance variable is the same. One is capitalized. Should look like this: