gpt4 book ai didi

ruby-on-rails - embeds_many 和 embeds_one 来自与 Mongoid 相同的模型

转载 作者:IT老高 更新时间:2023-10-28 13:28:50 25 4
gpt4 key购买 nike

我有两个模型,博客和主题。博客 embeds_many :themes 和 Theme embedded_in :blog。我也有 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

但是

# This DOES work!
class Blog
has_many :themes
has_one :theme
end

class Theme
belongs_to :blog
end

有人知道这是为什么吗?

更新

将主题之一分配给(选定的)主题也存在问题。

blog.themes = [theme_1, theme_2]
blog.save!

blog.theme = blog.themes.first
blog.save!

blog.reload
blog.theme # returns nil

最佳答案

使用这种方法,您将两次嵌入同一个文档:一次在主题集合中,然后在选定的主题中。

我建议删除第二个关系并使用字符串属性来存储当前主题名称。您可以执行以下操作:

class Blog
include Mongoid::Document
field :current_theme_name, type: String

embeds_many :themes

def current_theme
themes.find_by(name: current_theme_name)
end
end

class Theme
include Mongoid::Document
field :name, type: String

embedded_in :blog
end

请注意,mongoid 嵌入文档与主文档同时初始化,不需要额外的查询。

关于ruby-on-rails - embeds_many 和 embeds_one 来自与 Mongoid 相同的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7783450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com