I've spent hours on this one. I'm trying to use Ryan Bate's nested_form_for plugin in rails 3.2 though I don't think it's related to my issue. I tried taking it out and I still get the same issue.
When I hit organizations/:org_id/publications/new I see the form to add a new
publication correctly. However, when I submit (with or without correct data) it
I get an unknown attribute: publications_attributes error. I'm sure there's
something wrong with the way I'm building the related object(s) in the create
method. Any ideas?
models/organization.rb
class Organization < ActiveRecord::Base
attr_accessible :name,
:publications_attributes, # fk, nested form
has_many :publications
accepts_nested_attributes_for :publications,
:allow_destroy => true
models/publication.rb
class Publication < ActiveRecord::Base
attr_accessible :link,
:organization_id
belongs_to :organization
validates :link,
:presence => true,
end
controllers/publications_controller.rb
class PublicationsController < ApplicationController
def new
@organization = current_user.organizations.first
@organization.publications.build
end
def create
@organization = current_user.organizations.first
@organization.publications.build(params[:organization])
if @organization.save
flash[:notice] = "Successfully created publications"
redirect_to @organization
else
render :action => 'new'
end
end
end
routes.rb
resources :organizations do
resources :publications, :only => [:new, :create]
end
views/publications/new.html.erb
<%= nested_form_for @organization, :html => { :novalidate => 'novalidate' },
:method => :post,
:url => organization_publications_path, do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<%= f.fields_for :publications do |publication_form| %>
<%= render :partial => 'publications/form', :locals => { :f => publication_form } %>
<% end %>
<%= f.link_to_add "Add", :publications %>
<%= render :partial => 'shared/submit', :locals => { :text => 'Create', :f => f } %>
<% end %>
views/publications/_form.html.erb
<div class="field">
<%= f.label :link %>
<%= f.text_field :link %>
</div>
<%= f.link_to_remove "Remove" %>
The submitted hash looks like this:
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"rhW/m8mnulZMmW7gkLYxOT8RWYoQc8eYdp2hOXkqHPU=",
"organization"=>{
"publications_attributes"=>{
"0"=>{
"link"=>"fdsfdsfs"
}
}
},
"commit"=>"Create",
"organization_id"=>"53"
}