I have two models

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

and

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

in my parent controller i have

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

when i check for parent_id in custom_validation it returns me nil and got nil class error for parent.attribute_one as parent is nil what am I doing wrong here. Here is the backtrace

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)

it was a silly mistake I forget to add id in strong parameters for child.

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

solved.

2022 WebDevInsider