【发布时间】:2012-04-07 00:53:03
【问题描述】:
我真的被这个问题困住了,我找不到解决办法:
我有一个用户模型(用设计构建)。
我有一个项目模型,它是用户的嵌套资源。
在用户模型中(user.rb):
# Setup the relations model
has_many :items, :dependent => :destroy
在项目模型(item.rb)中:
# Setup the relations model
belong_to :user
在 routes.rb 中:
resources :users do
resources :items
end
通过这种方式,用户可以创建一个项目并拥有它:
路径前:user/1/items/1
现在我希望用户能够与另一个用户共享一个项目(由他创建),但拥有该项目的所有权(只有创建该项目的用户可以销毁它,并且只有创建该项目的用户可以销毁它创建的项目可以更新项目的某些字段,而不是其他字段也需要由收到项目的用户更新(可编辑)。 换句话说,我希望创建它的用户和刚刚接收它的用户对项目的权限是不同的。
为了允许用户之间的物品共享动作,我建立了以下 as_many :through 关系:
我创建了另一个模型,称为共享(表示项目模型和用户模型之间的联合表):
然后我通过以下方式修改了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
之后,我不得不考虑接收者也是用户(是自引用关系)的事实,并且在我的应用程序中,仍然存在友谊模型(允许用户与其他用户成为朋友)这就像一个魅力) - 但我相信乔尔的建议会有所帮助(或者只是改变对我朋友表的引用)。
有了这个,我可以为 Item (ItemsController) 创建一个 restful 控制器,并添加一个新的、创建、显示、销毁等操作,这些操作将允许用户(实际上是 current_user)创建、销毁或更新它没有任何问题。 (正如您在项目模型中看到的那样,有外键 user_id)。
为了创建一个restful控制器来管理共享模型(创建新的共享项目,并将它们分配(共享)给其他用户),我需要做什么???
我怎样才能调用数据库值?我的意思是,例如:
ID 为 3 的用户创建了五个新项目(项目 ID 为 1、2、3、4、5),现在他还决定与其他用户共享此项目的部分内容(项目 2 与用户 6,项目 4,5与用户 7,8,9)???
我把嵌套资源拉出来分享,现在我只有:
item 是用户的嵌套资源 (user/2/item/5) 分享会是什么??
请有人帮助我....
非常感谢 迪努兹
更新 我能够让应用程序正常工作,但仅作为单件:
用户创建一个项目。在他决定与另一个用户共享项目后(并使用共享控制器 - 联合表控制器,我能够在联合表内创建记录(传递用户 ID 和特定项目 ID)。
现在我想一次性完成所有操作:
current_user(登录的用户)创建一个项目,他需要有机会以相同的形式与其他用户(数组)共享它或只为自己保留。
我相信这进一步的步骤需要将项目控制器和共享控制器融合在一起,并在新的项目视图中做同样的事情。
那么我需要如何进行?如果有人可以为 has_many 建议一个好的教程:通过它可以涵盖我的情况(我真的需要了解在这种情况下控制器和视图的外观),我认为模型关联设置得很好,但是我无法真正弄清楚如何处理控制器和视图。
【问题讨论】:
标签: ruby-on-rails has-many-through nested-attributes