我是RoR的新手,在这个应用程序中,我想在用户取消付费服务后公开私人帖子。换句话说,在用户将帐户级别降级为标准级别后,用户的私人帖子将变为公共帖子。
以下是我如何处理这种情况:
订阅控制器:
def downgrade
subscription = current_user.subscription
if subscription.delete
downgrade_user_to_standard
current_user_downgrade_posts
flash[:success] = "Sorry to see you go."
redirect_to user_path(current_user)
else
flash[:error] = "Can't downgrade at this moment."
redirect_to root_path
end
end
应用程序控制器:
protected
def downgrade_user_to_standard
current_user.update_attributes(role: "standard")
end
def current_user_downgrade_posts
privateposts = current_user.posts.where(private: true)
privateposts.each do |privatepost|
privatepost.posts_update_attributes(private: false)
end
end
当我在服务器和控制台上测试它时,我发现在将高级用户降级到标准级别后,之前创建的私人帖子并没有像预期的那样公开。由于我运行rails服务器时没有出现错误消息,有人能向我指出我错过了哪些步骤以及如何使其正常工作吗?
提前谢谢!
我认为代码不应该在控制器中,但。。。
您应该更改:
privatepost.posts_update_attributes(private: false)
带有:
privatepost.update_attribute(:private, false)
如果你不关心验证、回调和触摸时间戳,那么你可以删除循环并使用:
current_user.posts.where(private: true).update_all(private: false)