RoR: NoMethodError when executing delete_all for a has_many relationship

后端 未结 5 1917
眼角桃花
眼角桃花 2021-01-22 18:01

My classes are as follows, with Customer inheriting from User using the single-table inheritance approach. User has attributes name and email while Order has destination.

<
相关标签:
5条回答
  • 2021-01-22 18:09

    It seems you have no inverse associations and Rails fails to resolve the order's customer when updating the cached counters. Try this:

    class Customer < User
      has_many :orders, inverse_of: :customer
    end
    
    class Order < ActiveRecord::Base
      belongs_to :customer, inverse_of: :orders
    end
    
    0 讨论(0)
  • 2021-01-22 18:21

    for delete_all

    for example

     Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
      Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
    

    for destroy_all

    for example

     Person.destroy_all("last_login < '2004-04-04'")
      Person.destroy_all(:status => "inactive")
    
    0 讨论(0)
  • 2021-01-22 18:22

    I guess you were right about the problem about the ruby version. I found this question.

    The guy had a similar problem and he fixed it by switching his ruby version from ruby-2.2.0 to ruby-2.1.1.

    If it's not the ruby version, it could be the ActiveRecord Version.

    0 讨论(0)
  • 2021-01-22 18:24

    This is the Rails issue with Ruby 2.2.2: https://github.com/rails/rails/issues/18991 . It's closed and fixed in 3.2.22).

    0 讨论(0)
  • 2021-01-22 18:27

    Try updating you Customer class association with

    has_many :orders, :dependent => :destroy
    

    or

    has_many :orders, :dependent => :delete_all
    

    Depending on what you want to achieve.

    :destroy causes all the associated objects to also be destroyed.

    :delete_all causes all the associated objects to be deleted directly from the database without executing callbacks.

    0 讨论(0)
提交回复
热议问题