Hei Matau Hei Matau - 2 months ago 16
Ruby Question

NoMethodError, ActiveRecord 4.0

I'm trying to delete, not destroy (that doesn't work either), a record as a learning exercise for Rails.

In the rails console, I execute:

subject.pages.delete(second_page)
and I get the below error message (same for trying destroy).


NoMethodError: undefined method `name' for nil:NilClass


In subject.pages is:

=> #<ActiveRecord::Associations::CollectionProxy [#<Page id: 2, subject_id: 1, name: "First Page", permalink: "first", position: 1, visible: false, created_at: "2016-08-19 17:58:02", updated_at: "2016-08-19 17:58:02">, #<Page id: 3, subject_id: 1, name: "Second Page", permalink: "second", position: 2, visible: false, created_at: "2016-08-19 17:59:07", updated_at: "2016-08-19 17:59:07">]>


Subject has a one to many relation with pages. Page belongs_to subject.

Ed1: It looks like 'second_page' is a local variable. So when I exited the Rails Console. I wasn't able to recreate the problem, yet I still can't delete this record.

Ed2: So, I decided to continue my learning and I didn't run into any hiccups until I used ERB calling
subject.pages.size
. Again, I got a 'NoMethodError', where the html.erb file wouldn't render. Where should I be checking to make sure I'm declaring pages correctly? I double checked the teacher's code and it all looks the same (I could be missing something minor) but I'm lost on how to fix this error in my app.

Ed3(Final): I dropped the tables created and started over. I'm not sure what the solution actually was but I do think changing the relationship in the controller did help. Thanks for helping.

Using: Rails 4.0.0, ActiveRecord 4.0.0, MySQL 5.17.14 (If more information is needed, I'll update promptly)

Answer

According to the APIdock for delete(*records)

For has_many associations, the deletion is done according to the strategy specified by the :dependent option.[...] If no :dependent option is given, then it will follow the default strategy. The default strategy is :nullify. This sets the foreign keys to NULL.

That means the record is not destroyed, only the association. You have to set the dependent option to :destroy to delete the record from database.

class Subject < ActiveRecord::Base
  has_many :pages, dependent: :destroy
end
Comments