【发布时间】:2012-09-26 18:55:27
【问题描述】:
我正在建立一个协作写作平台。用户可以拥有项目集,其中任何项目都可以在任何集中并属于任何用户。但这会导致一些问题。
这些是我的模型关系:
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
我无法弄清楚正确处理此问题的“rails 方式”。
问题一:
创建新项目时,仅存储集合/项目关联,而不存储用户:
class ItemsController < ApplicationController
def create
@set = current_user.sets.find(params[:set_id])
@set.where(title: params[:item][:title]).first_or_create!
end
end
*更新*
要解决问题 1,我能想到的最好办法是执行以下操作:
@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!
感觉很不对劲!
问题 2:
假设关联表从问题 1 中正确填充,以下控制器将返回集合拥有的所有项目,但忽略用户所有权:
class SetsController < ApplicationController
def index
@sets = current_user.sets.includes(:items)
end
end
*更新*
仍然没有运气找到答案。 为了更好地解释这个问题:
以下将只返回属于当前用户的集合
@sets = current_user.sets.all
但是,以下将仅返回用户的集合,但将包括集合的所有项目,即使它们不属于当前用户。换句话说,用户范围被删除了。
@sets = current_user.sets.includes(:items)
我整天都在努力解决这个问题,但似乎找不到线索
【问题讨论】:
-
将其分解为 1:Many's... 创建集合实例。
标签: ruby-on-rails ruby has-many-through named-scope nested-includes