san*_*ius 6 ruby ruby-on-rails mongodb mongoid
我有两个模型,博客和主题.博客embeds_many:主题和主题embedded_in:博客.我还有Blog embeds_one:theme(用于激活的主题).这不起作用.创建主题时blog.themes.create,不存储主题.如果我更改了集合,那么它们就不会被嵌入,一切正常.
# This does NOT work!
class Blog
embeds_many :themes
embeds_one :theme
end
class Theme
embedded_in :blog
end
Run Code Online (Sandbox Code Playgroud)
但
# This DOES work!
class Blog
has_many :themes
has_one :theme
end
class Theme
belongs_to :blog
end
Run Code Online (Sandbox Code Playgroud)
有谁知道这是为什么?
将主题之一分配给(选定)主题也存在问题.
blog.themes = [theme_1, theme_2]
blog.save!
blog.theme = blog.themes.first
blog.save!
blog.reload
blog.theme # returns nil
Run Code Online (Sandbox Code Playgroud)
好的,所以我遇到了同样的问题,并且认为我刚刚偶然发现了解决方案(我正在检查关系元数据的代码)。
尝试这个:
class Blog
embeds_many :themes, :as => :themes_collection, :class_name => "Theme"
embeds_one :theme, :as => :theme_item, :class_name => "Theme"
end
class Theme
embedded_in :themes_collection, :polymorphic => true
embedded_in :theme_item, :polymorphic => true
end
Run Code Online (Sandbox Code Playgroud)
我的猜测是:
:themes)实际上成为方法名称。:as建立实际的关系,因此需要它们在两个类中匹配。:class_name看起来很明显,用于实际序列化数据的类。希望这会有所帮助 - 我显然不是 mongoid 内部工作的专家,但这应该足以让你运行。我的测试现在是绿色的,并且数据正在按预期进行序列化。
| 归档时间: |
|
| 查看次数: |
2012 次 |
| 最近记录: |