我有一位嵌入了很多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
答案 0 :(得分: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
- > 用户有许多 EmailAccounts ,其中嵌入了 EmailTemplates 。
然后你可以这样做:
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
要回答你的第一个问题,我认为这是可能的,但肯定不是正确的方式去这里。 :)
希望它有所帮助。