matcha
matcha

Reputation: 443

Mongoid creating embedded document from a view

I am trying to add a embed a Profile into a User and I keep getting this error.

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

I am sure it's a simple problem to fix but I have no clue how to do it. I am very new with RoR so things are still a little confusing. Here is my code.

Models/Profile

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

  field :handle
  field :description
  embedded_in :user
end

Controllers/Profile

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

Views/profile/new

<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 %>

Upvotes: 0

Views: 1761

Answers (2)

Bram
Bram

Reputation: 11

You cannot use Profile.create in your views.html.erb because Profile is embedded in a user. So you need to do something like current_user.build_profile

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

should work

Upvotes: 1

sandrew
sandrew

Reputation: 3129

try

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

Upvotes: 0

Related Questions