【问题标题】:Nested Form: "Cannot call create unless the parent is saved" error嵌套表单:“除非保存父级,否则无法调用创建”错误
【发布时间】:2013-02-02 23:15:26
【问题描述】:

我有一个嵌套表单,其中每个帖子都有并属于许多位置。使用嵌套表单向帖子添加位置就可以了。但是,当我单击“编辑”并更改除位置以外的任何内容时,我得到了 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
...

location.rb(模型) 包括 PublicActivity::Model 跟踪 跟踪所有者:Proc.new{ |控制器,模型|控制器.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'

【问题讨论】:

  • 你能显示错误实际发生的应用程序代码行吗?
  • 嗨@moritz,它实际上发生在after_save { |venue| venue.destroy if venue.name.blank? } 线上。如果我对此发表评论,它会修复它。我不敢相信这很容易。 打自己的额头

标签: ruby-on-rails ruby ruby-on-rails-3 model


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 2021-04-01
    相关资源
    最近更新 更多