我真的被困在这个问题上,我不能找到一种方法,从它问世:嵌套的资源有很多:通过关系问题
我有一个用户模式(内置了色器件)。
我拥有的项目模型,是用户的嵌套资源。
在用户模型(user.rb):
# Setup the relations model
has_many :items, :dependent => :destroy
在项目模型(item.rb的):
resources :users do
resources :items
end
:
# Setup the relations model
belong_to :user
在routes.rb中
以这种方式,用户能够创建一个项目,并拥有它:
ex of path:user/1/items/1
现在我希望用户能够与另一个用户共享一个项目(由他创建),但是保留项目的所有权(只是用户创建该项目的用户可以销毁该项目,并且只有创建该项目的用户可以更新该项目的某个字段,而其他字段也需要由用户接收该项目才能更新(可编辑))。 换句话说,我希望项目的权限对于创建它的用户和刚接收它的用户是不同的。
为了让用户之间分享内容的动作,我建立以下as_many:通过关系:
我创造了另一个模型,称为共享(代表项目模型和用户之间的接合表模型):
然后我修改以下列方式的user.rb(用户模型):
# Setup the Item relations model
has_many :items, :dependent => :destroy # this to set up the item ownership
#This to set up the has_many :through realtionship
#(note I am calling a new model shared_items - that really doesn't exist - is an item model)
has_many :sharings
has_many :shared_items, :foreign_key => "shared_user_id", :through => :sharings
accepts_nested_attributes_for :items #This will work for the nested items resource
accepts_nested_attributes_for :sharings #Do I really need this line??
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation,
:items_attributes, #This will work for the nested items resource
:sharings_attributes #Do I really need this line??
然后我修改以下列方式的item.rb的(项目模型):
# Setup the relations model
belong_to :user
#this two lines are suppose to connect the two models (item and receiver) using a joint table
has_many :sharings
has_many :shared_users, :foreign_key => "shared_item_id", :through => :sharings
accepts_nested_attributes_for :sharings #Do I really need this line??
attr_accessible :user_id, :item_type, :reference_date, :title,
:sharings_attributes #Do I really need this line??
我写的sharing.rb(共享模式 - 联合表),以下列方式:
belongs_to :shared_user, :class_name => "User"
belongs_to :shared_item, :class_name => "Item"
attr_accessible :shared_moment_id, :shared_user_id
后,我不得不考虑的是,接收器也是一个用户(是自我参考关系),并且在我的应用程序中,仍然存在友情模型(允许用户与其他用户进行交流,这就像一种魅力) - 但我相信Joel的建议可以帮助(或者只是改变参考我的朋友表)。
在这里,我可以为Item(ItemsController)创建一个宁静的控制器,并添加一个新的,创建,显示,销毁等操作,允许用户(实际上是current_user)创建一个项目,销毁或更新它没有任何问题。 (正如你可以在项目模型中看到的那样有外键user_id)。
我需要做的,以创造一个宁静的控制器来管理共享模式(创建新的共享项目,并把它们(分享)与其他用户分配),而不是什么???
后如何我记得数据库值?我的意思是,例如:
用户ID为3创建了五个新项目(同项目编号1,2,3,4,5),现在他也决定要分享一些与其他用户(第2项与本项目用户6,具有用户7,8,9项4,5)???
我拉出了共享嵌套的资源,现在我只是有:
产品的用户一个嵌套的资源(用户/ 2 /项/ 5) 共享将是什么?
请人帮我....
非常感谢 Dinuz
UPDATE 我能够让正常工作的应用程序,但由于只有单件:
的用户创建一个项目。在他决定与另一个用户共享该项目(并使用分享控制器 - 联合表格控制器后,我能够在联合表格内创建记录(传递用户标识和特定项目标识)
现在我想代之以一次性执行所有操作:
current_user(登录的用户)创建一个项目,并且他需要以相同的形式有机会与其他人共享用户(阵列)或只是为自己保留。
我相信,这一进一步的步骤,需要融化在一起的项目控制器和共享控制器,并在新项目视图中做同样的事情。
那么如何我需要继续吗?如果有人可以为has_many提出一个很好的教程:通过它可以覆盖我的案例(我真的需要了解在这种情况下控制器和视图的外观),我认为模型关联设置得很好,但是我无法真正弄清楚如何与控制器和视图进行。
嗨乔尔,你的想法是一个很好的,但我需要弄清楚我需要如何设置模型中的关联 – Dinuz 2012-04-07 23:54:23
我要编辑我的文章,以更新问题。 – Dinuz 2012-04-07 23:56:11
好吧,我解决了这个问题....再次感谢joel! – Dinuz 2012-04-14 22:07:18