James Osborn
James Osborn

Reputation: 187

Nested Form: "Cannot call create unless the parent is saved" error

I have a nested form where each post has and belongs to many locations. Adding locations to a post with the nested form works just fine. However when I click 'edit' and change anything except a location I get passed the cannot call create unless the parent is saved error.

I'm guessing this is something to do with the bit of code in my model which runs through the location_attributes being submitted and checks them for uniqueness however I have no idea how to fix this. I have tried just @post.save! before I do find_or_initialize_by_name in the controller but get the same error.

Code is below. I know this is pretty unique to me but any suggestions would be great!

posts_controller.rb

...
def update
   location_set = params[:post].delete(:locations_attributes) unless params[:post][:locations_attributes].blank?
  @post = Post.find(params[:id])
  @post.locations = Location.find_or_initialize_location_set(location_set) unless location_set.nil?

  if @post.update_attributes(params[:post])
    redirect_to @post, notice: 'Blog post was successfully updated.'
  else
    render action: "edit"
  end
end
...

location.rb (model) include PublicActivity::Model tracked tracked owner: Proc.new{ |controller, model| controller.current_user }

include FriendlyId
friendly_id :name

after_save { |location| location.destroy if location.name.blank? }
after_save { |venue| venue.destroy if venue.name.blank? }


has_many :location_post, :order => "position"
has_many :posts, :through => :location_post, :order => 'location_posts.position'


attr_accessible :latitude, :longitude, :name, :post_id, :notes, :asset, :assets_attributes, :venues_attributes
attr_accessor :_destroy, :position, :location_post_id


def self.find_or_initialize_location_set(location_set)
  #create a locations array
  locations = []

  locations = locations.delete_if { |elem| elem.flatten.empty? }
  location_set.each do |key, location|
    if location.delete(:_destroy) == "1"
      locations.delete_if {|elem| elem[:name] == location[:name]}
    else
  locations << find_or_initialize_by_name(location)  
  #REMINDER In rails 4 this must be written as where(...).first_or_create
    end
end
locations
end

*EDIT - The Error *

app/models/location.rb:10:in `block in <class:Location>'
app/controllers/blogit/posts_controller.rb:97:in `update'

Upvotes: 0

Views: 1129

Answers (1)

James Osborn
James Osborn

Reputation: 187

This was caused by a stupid mistake.

The line after_save { |venue| venue.destroy if venue.name.blank? } is no longer relevant.

I'm an idiot and didn't read the error properly. Thanks for all those who helped.

Upvotes: 1

Related Questions