dimanche 24 mai 2015

Many-to-zero mongoid relation causing other model to update anyway, Devise session dropping

I have a problem with Devise giving me 401 Unauthorized after creating a new user and referencing models in a callback (I use a custom cms, based on Rails 3.2.18 and Devise 3.4.1). Here's my models:

class User
  ...
  after_create :initialize_conversations

  def initialize_conversations
    user = self
    User.where(category: 'admins').each do |interlocutor|
      Conversation.create!(posters: [user, interlocutor])
      #I am logged in as admin, so one of the instances has my account as interlocutor
    end
  end
end

class Conversation
  ...
  has_and_belongs_to_many :posters, class_name: 'User', inverse_of: nil
  #all callbacks switched off
end

So what I am trying to do is to create new User while being logged in as admin User. It worked fine until I introduced Conversation model. Then I started to get 401 after succesful creation of user and conversations. I checked logs, and noticed that on create of each Conversation I also get this for each of my posters:

MOPED: 127.0.0.1:27017 UPDATE       database=blahblah_development collection=users selector={"_id"=>"54ee69e81d41c82b6c000001"} update={"$set"=>{"encrypted_password"=>"$2a$10$EPQXkBuYcd7rc1FiJTPngOlrpLAqw99O4Rja4zhuIMVzv838RQEyW"}} flags=[] (0.4256ms)

What? But it supposed to be many-to-zero, right? Each time encrypted_password is new, and then everything goes south despite that create action actually goes well: ... database stuff ends Redirected to http://ift.tt/1Fagc3P Completed 302 Found in 3283.6ms

Started GET "/admin/users" for 192.168.78.1 at 2015-05-25 03:07:01 +0200
Processing by UsersController#index as HTML
MOPED: 127.0.0.1:27017 QUERY        database=blahblah_development collection=users selector={"$query"=>{"_id"=>"54ee69e81d41c82b6c000002"}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (1.8945ms)
MOPED: 127.0.0.1:27017 QUERY        database=blahblah_development collection=users selector={"$query"=>{"_id"=>"54ee69e81d41c82b6c000002"}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (1.2648ms)
Completed 401 Unauthorized in 20.0ms

My ConversationsController is vanilla, and UsersController is simple too:

class UsersController < ApplicationController
  before_filter :authenticate_user!
  protect_from_forgery

  def index
    @users = User.all.asc(:last_name).paginate page: (params[:page] || 1)
  end
  ...
end

What am I to do? Can I reference many-to-zero in a way that doesn't update my users collection, or at least not updating encrypted_password, which makes no sense? Or am I completely missing something? Serialized hash doesn't get affected at all, so I am a bit confused about the cause of session drop.

Aucun commentaire:

Enregistrer un commentaire