Mongoid从视图创建嵌入文档

问题描述:

我想添加一个嵌入配置文件到用户,我不断收到此错误。Mongoid从视图创建嵌入文档

Access to the collection for Profile is not allowed since it is an embedded document, please access a collection from the root document. 

我相信这是一个简单的问题来解决,但我不知道该怎么做。我对RoR很新,所以事情还是有点混乱。这是我的代码。

型号/配置文件

class Profile 
    include Mongoid::Document 
    attr_accessible :handle, :description 

    field :handle 
    field :description 
    embedded_in :user 
end 

控制器/简介

class ProfileController < ApplicationController 
    def create 
    @user = current_user 
    @profile = @user.profile.create!(params[:profile]) 
    redirect_to dashboard_path 
    end 
end 

查看/资料/新

<h1>Create Profile</h1> 

<%= form_for [:current_user, Profile.create] do |f| %> 
<div class="field"> 
    <%= f.label :handle %> 
    <%= f.text_field :handle %> 
</div> 
<div class="field"> 
    <%= f.label :description %> 
    <%= f.text_area:description %> 
</div> 

    <p class="button"><%= f.submit %></p> 
<% end %> 

尝试

@user = current_user 
@profile = Profile.new(params[:profile]) 
@user.profile = @profile 
@user.save 
# or @profile.save 
+0

我收到同样的错误消息。 – MattAitchison 2011-05-21 17:01:14

+0

用户模型中是否有“embeds_one:profile”? – sandrew 2011-05-21 21:48:19

+0

是的。你想让我发布吗? – MattAitchison 2011-05-22 02:47:11

您的views.html.erb中不能使用Profile.create,因为Profile已嵌入到用户中。所以,你需要做一些像current_user.build_profile

<%= form_for [:current_user, current_user.build_profile] do |f| %> 

应该工作