Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 制作一个有许多关系避免孩子们存储家长的id_Ruby On Rails_Mongoid - Fatal编程技术网

Ruby on rails 制作一个有许多关系避免孩子们存储家长的id

Ruby on rails 制作一个有许多关系避免孩子们存储家长的id,ruby-on-rails,mongoid,Ruby On Rails,Mongoid,我希望用户有一个收藏夹数组,但在项目集合中,不存储用户id。我采用的方法正确吗 如果我尝试以user.last.favorites的身份访问用户收藏夹,或者尝试向用户添加收藏夹,则需要花费很长时间。为什么会这样 谢谢我相信您缺少Item类中的嵌入用户 前面的代码应该可以工作,并且不允许您将用户id保存在收藏夹中 因此,这段代码应该适用于user.last.favorites=>[Array of favorites] 但此代码将通过异常user.last.favorites.last.user=

我希望用户有一个收藏夹数组,但在项目集合中,不存储用户id。我采用的方法正确吗

如果我尝试以user.last.favorites的身份访问用户收藏夹,或者尝试向用户添加收藏夹,则需要花费很长时间。为什么会这样


谢谢

我相信您缺少Item类中的嵌入用户

前面的代码应该可以工作,并且不允许您将用户id保存在收藏夹中

因此,这段代码应该适用于user.last.favorites=>[Array of favorites] 但此代码将通过异常user.last.favorites.last.user=>方法user not found执行

为什么要花很长时间?!除非我看过日志,否则我无法判断。 也不要使用嵌入式解决方案,嵌入式集合只能从父级访问。。。我认为这不是你想要达到的

简单地说:如果您有一个叫做“rails”的收藏夹, 使用另一个答案中描述的嵌入式解决方案将导致以下行为

class User
  include Mongoid::Document
  has_many :favorites, class_name: "Item"
end

class Item
 # class is all lower case
 include Mongoid::Document
 # remove the relation to the user form the item
 # so that it cannot save the user_id 
end

妈的,对不起,我看错了你的第一篇帖子。您是否使用了RoboMongo之类的工具来查看哪些数据正在被持久化?has-many可能正在存储与项目对应的ID数组。我会查一查。尝试查看服务器日志以查看查询的外观。我对Mongoid没有什么经验
class User
  include Mongoid::Document
  has_many :favorites, class_name: "Item"
end

class Item
 # class is all lower case
 include Mongoid::Document
 # remove the relation to the user form the item
 # so that it cannot save the user_id 
end
p Favorites.all.to_a
#=> []
p user.first.favorites.first
#=> <Favorite id: 1, name: rails>
p user.last.favorites.first
#=> <Favorite id: 100, name: rails>
p Favorites.all.to_a
#=> [<<Favorite id: 1, name: rails>]
p user.first.favorites.first
#=> <Favorite id: 1, name: rails>
p user.last.favorites.first
#=> <Favorite id: 1, name: rails>

# this is pseudocode but you will get the idea
user.last.favorites.first.name = `rails4` # then save

p user.first.favorites.first
#=> <Favorite id: 1, name: rails4>
p user.last.favorites.first
#=> <Favorite id: 1, name: rails4>