我有一个嵌套表单,其中每个帖子都有并且属于许多位置。使用嵌套表单向帖子添加位置效果很好。但是,当我单击"编辑"并更改除位置以外的任何内容时,我会收到cannot call create unless the parent is saved
错误。
我猜这与我的模型中的代码有关,该代码贯穿正在提交location_attributes
并检查它们的唯一性,但我不知道如何解决这个问题。在控制器中find_or_initialize_by_name
之前,我已经尝试了@post.save!
,但得到了相同的错误。
代码如下。我知道这对我来说非常独特,但任何建议都会很棒!
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
...
位置.rb (模型) 包括公共活动::模型 跟踪 跟踪的所有者: 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'
这是由一个愚蠢的错误引起的。
行after_save { |venue| venue.destroy if venue.name.blank? }
不再相关。
我是个白痴,没有正确阅读错误。感谢所有帮助过的人。