Mongoid从视图创建嵌入式文档

时间:2011-05-21 05:48:13

标签: ruby-on-rails mongodb 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 %>

2 个答案:

答案 0 :(得分:1)

您无法在Profile.create中使用views.html.erb,因为Profile已嵌入用户中。所以你需要做current_user.build_profile

之类的事情
<%= form_for [:current_user, current_user.build_profile] do |f| %>

应该有效

答案 1 :(得分:0)

尝试

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