Weird relationship behavior on Rails 3 and update_attribute

我是研究僧i 提交于 2019-12-06 15:58:22

Try adding a @user.reload call before @user.leave_group in the test.

Even though the user record is updated with it's group in the DB when you create @group_2 from the factory, I suspect the @user object is not. Then you call leave_group! with a @user with a group ID of nil, so the save won't do anything because the object is unchanged. Then in the next line of your test you reload the @user, which now has the group_id from the DB assigned earlier.

try to chance the model class as following:

class User < ActiveRecord::Base
  # Associations
  has_one :own_group, :class_name => "Group", :foreign_key => "owner_id"
  belongs_to :group

  def leave_group!
    group_randomize_owner
    self.group.clear
  end

  private

  def group_randomize_owner
    if group.owner == self
      group.randomize_owner!
    end
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!