1

我有一个嵌入许多 email_accounts 的用户。同时我希望 email_accounts 可以有多个 email_templates。这可能吗?当我尝试合并它时,我的 Rails 应用程序拒绝接受关系。

我希望进行如下查询:

email_template = EmailTemplate.first
email_template.email_account = current_user.email_accounts.where(:_id => params[:email_account_id).first

以下是关系:

class User
  include Mongoid::Document
  embeds_many :email_accounts, :inverse_of => :user
  has_many :email_templates, :inverse_of => :user
end

class EmailAccount
  include Mongoid::Document
  embedded_in :user, :inverse_of => :email_accounts
  has_many :email_templates :inverse_of => :email_account
end

class EmailTemplate
  include Mongoid::Document
  belongs_to :user, :inverse_of => :email_templates
  belongs_to :email_account, :inverse_of => :email_templates
end
4

1 回答 1

2

您可以尝试稍微改变一下您的关联:

class User
  include Mongoid::Document
  has_many :email_accounts
end

class EmailAccount
  include Mongoid::Document
  belongs_to :user
  embeds_many :email_templates :inverse_of => :email_account
end

class EmailTemplate
  include Mongoid::Document
  embedded_in :email_account, :inverse_of => :email_templates
end

--> 一个用户有很多嵌入了EmailTemplates的EmailAccounts

然后你可以这样做:

email_account = current_user.email_accounts.find(params[:email_account_id])
email_account.email_templates << EmailAccount.all.map(&:email_templates).flatten.first

您不能以这种方式访问​​嵌入式文档:

email_template = EmailTemplate.first

您必须先通过 EmailAccount:

email_template = EmailAccount.all.map(&:email_templates).flatten.first

要回答您的第一个问题,我认为这是可能的,但肯定不是正确的方法。:)

希望能帮助到你。

于 2013-05-11T23:34:20.437 回答