Search code examples
ruby-on-rails-3nested-formsformtastic

accepts_nested_attributes_for Formtastic nested form


I have looked at other posts and can't see what I'm doing wrong. I'm getting this error:

ActiveModel::MassAssignmentSecurity::Error in ProjectsController#create

Can't mass-assign protected attributes: blog_post

Here are my two models and my form. I'm under the impression that there's nothing special that needs to be in the project controller. Is there anything in the project or blog_post controller that could screw this up?

project.rb

class Project < ActiveRecord::Base
  attr_accessible :name, :category_id, :user_id, :goal, :about, :headline, :image_url, :about_html, :blog_post_attributes

  has_many :blog_posts, :dependent => :destroy
  accepts_nested_attributes_for :blog_posts
end

blog_post.rb

class BlogPost < ActiveRecord::Base
  attr_accessible :project_id, :user_id, :title, :blog_text, :commentable, :private
  belongs_to :project
  has_many :blog_post_replies, :dependent => :destroy
end

projects/_new_form.html.erb

<%= semantic_form_for @project do |f|  %>
<%= f.semantic_errors :state %>

<%= f.input :name, :as => :string %>
<%= f.input :headline, :as => :string %>
<%= f.input :about %>
<%= f.input :image_url, :as => :file %>
<%= f.input :category , :include_blank => false%>
<div class="well">
<%= f.semantic_fields_for :blog_post do |blog_post| %>
    <%= blog_post.input :title, :as => :string, :label => "First Blog Post Title" %>
    <%= blog_post.input :blog_text, :as => :text, :label => "First Blog Post Text" %>
<% end %>
</div>
<%= f.action :submit, :as => :button %>
<% end %>

EDIT If I use the suggested Formtastic format:

<%= f.input :title, :for => :blog_post %>
<%= f.input :blog_text, :for => :blog_post %>

I get this error; which makes me think it's not seeing the nested attributes at all:

NoMethodError in Projects#new

undefined method `title' for #<Project:0x007fb044745f58>

Solution

  • The error is here:

    <%= f.semantic_fields_for :blog_post do |blog_post| %>
    

    It should be:

    <%= f.semantic_fields_for :blog_posts do |blog_post| %>
    

    (:blog_posts instead of :blog_post)