更新父级时未设置父级ID

时间:2016-01-01 06:39:11

标签: ruby-on-rails ruby postgresql ruby-on-rails-4 activerecord

我有两个型号

class Parent < ActiveRecord::Base
  has_one :child
  accepts_nested_attributes_for_child :child
end

class Child < ActiveRecord::Base
  belongs_to :parent
  validates :parent, :attribute_one, presence: true
  validate :custom_validation

  def custom_validation
    if self.attribute_one > parent.attribute_one
      errors.add(:base, "error message")
    end
  end
end

在我的父控制器中我有

def update
  @parent = Parent.find(params[:id])    
  @parent.update_attributes(parent_params) #here is problem
end

private

  def trasnfer_params
    params.require(:parent).permit(:attribute_one, :attribute_two, child_attributes:[:parent_id, :attribute_one])
  end

当我在custom_validation中检查parent_id时,它返回nil并为parent.attribute_one得到nil类错误,因为parent是nil我在这里做错了什么。 这是回溯

NoMethodError (undefined method `attribute_one' for nil:NilClass):
  app/models/child.rb:8:in `custom_validation'
  app/controllers/parents_controller.rb:12:in `update'


  Rendered vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (4.6ms)
  Rendered vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.6ms)
  Rendered vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.8ms)
  Rendered vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb (19.6ms)
  Rendered vendor/bundle/ruby/2.2.0/gems/web-console-2.1.1/lib/web_console/templates/_markup.html (0.4ms)
  Rendered vendor/bundle/ruby/2.2.0/gems/web-console-2.1.1/lib/web_console/templates/style.css within layouts/inlined_string (0.5ms)
  Rendered vendor/bundle/ruby/2.2.0/gems/web-console-2.1.1/lib/web_console/templates/_inner_console_markup.html within layouts/inlined_string (0.4ms)
  Rendered vendor/bundle/ruby/2.2.0/gems/web-console-2.1.1/lib/web_console/templates/_prompt_box_markup.html within layouts/inlined_string (0.3ms)
  Rendered vendor/bundle/ruby/2.2.0/gems/web-console-2.1.1/lib/web_console/templates/console.js within layouts/javascript (17.9ms)
  Rendered vendor/bundle/ruby/2.2.0/gems/web-console-2.1.1/lib/web_console/templates/main.js within layouts/javascript (0.3ms)
  Rendered vendor/bundle/ruby/2.2.0/gems/web-console-2.1.1/lib/web_console/templates/error_page.js within layouts/javascript (0.4ms)
  Rendered vendor/bundle/ruby/2.2.0/gems/web-console-2.1.1/lib/web_console/templates/index.html (34.4ms)

1 个答案:

答案 0 :(得分:1)

这是一个愚蠢的错误,我忘记在孩子的强参数中添加id。

def trasnfer_params
  params.require(:parent).permit(:attribute_one, :attribute_two, child_attributes:[:id, :parent_id, :attribute_one]) #added id in child_attributes
end

解决。