我有一个嵌套的表单,每个帖子都有,并且属于许多位置。使用嵌套表单向帖子添加位置效果很好。但是,当我单击“编辑”并更改除位置之外的任何内容时,我会传递cannot call create unless the parent is saved
错误。
我猜这与我的模型中的一些代码有关,它通过提交的location_attributes
运行并检查它们的唯一性但是我不知道如何解决这个问题。我在控制器中@post.save!
之前尝试了find_or_initialize_by_name
,但得到了同样的错误。
代码如下。我知道这对我来说非常独特,但任何建议都会很棒!
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(型号) 包括PublicActivity :: Model 追踪 跟踪所有者: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
* 编辑 - 错误*
app/models/location.rb:10:in `block in <class:Location>'
app/controllers/blogit/posts_controller.rb:97:in `update'
答案 0 :(得分:1)
这是由一个愚蠢的错误引起的。
行after_save { |venue| venue.destroy if venue.name.blank? }
不再相关。
我是个白痴,并没有正确阅读错误。感谢所有帮助过的人。