0

我有一个嵌套表单,其中每个帖子都有并属于许多位置。使用嵌套表单向帖子添加位置就可以了。但是,当我单击“编辑”并更改除位置以外的任何内容时,我得到了cannot call create unless the parent is saved错误。

我猜这与我的模型中的一些代码有关,它贯穿location_attributes提交并检查它们的唯一性,但我不知道如何解决这个问题。我刚刚@post.save!find_or_initialize_by_name控制器中尝试过,但得到了同样的错误。

代码如下。我知道这对我来说非常独特,但任何建议都会很棒!

post_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) 包括 PublicActivity::Model tracked tracked owner: Proc.new{ |controller, model| 控制器.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

*编辑 - 错误 *

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

1 回答 1

1

这是一个愚蠢的错误造成的。

该行after_save { |venue| venue.destroy if venue.name.blank? }不再相关。

我是个白痴,没有正确阅读错误。感谢所有帮助过的人。

于 2013-02-03T15:14:02.600 回答