0

I added some after create do and before update do code to my model and now I cant save my posts btw both models(user & posts) have a has_and_belongs_to_many relationship:

after_create do
@post = Post.find(self.id)

       for user in  @post.managers.split(',')
     @user = User.find_by_email(user)
    @post.user << @user
    @post.save
  end
end


before_update do
   #
 @post = Post.find(self.id)
       for user in  @post.managers.split(',')

      @user = User.find_by_email(user)
      if @post.user.include?(user)
          #do nothing
      else
    @post.user << @user
   @post.save

end
 end 

What's causing this and what do I change to get rid of this error?

  • Some quick hints: you don't need to re-read the current object in any of the hooks. self is already the object you want! Stack overflow errors are caused by endlessly recursive code. Think about what happens when you call save on @post in your before_update...it's going to call before_update again. – struthersneil Aug 13 '17 at 20:07
  • @struthersneil ohhhh....... so if I just use self.user it'll work? –  Aug 13 '17 at 20:14
  • Yep! And don't call save inside the before_update hook. – struthersneil Aug 13 '17 at 20:19
  • 1
    @struthersneil thanks for the help really appreciate it. –  Aug 13 '17 at 20:23
  • You might find that using a single before_save hook will accomplish all of your needs and avoid the repetition too, as it will fire on object creation and object update. – struthersneil Aug 13 '17 at 20:25
  • also `@post.user << @user` looks odd. if `@post.user` is an array, shouldn't it be `@post.users`? – max pleaner Aug 13 '17 at 23:15
  • @maxpleaner I actually tried using plurals but it didn't work –  Aug 14 '17 at 11:25

0 Answers0