GVS GVS - 1 year ago 70
Ruby Question

Ruby: Automatically create a post when user updates profile picture

Users have the ability to create posts. They can also add (and update) their profile picture.

But I want to take this a step further. When a user updates their profile picture, I want the user to automatically create a post that says "Username updated their profile picture" and display the image below.

I am new to ruby and ruby on rails, I started learning about 1 month ago, so I could be wrong, but I was thinking I could achieve this with an if statement, such as:

if @user.avatar.save do
#Post automated post

I commented because I have no idea what to type. But I know that someone with more knowledge could guide me (and the community) on how to achieve this.

Answer Source

You may try using after_update callback in your User model. This will call create_avatar_post method every time user avatar is successfully updated:

# This is in your user.rb file
class User < ApplicationRecord
    # Include default devise modules. Others available are:
    # :confirmable, :lockable, :timeoutable and :omniauthable
    devise :database_authenticatable, :registerable,
           :recoverable, :rememberable, :trackable, :validatable

    has_many :posts, dependent: :destroy
    has_many :likes, dependent: :destroy
    has_many :liked_posts, through: :likes, source: :post

    validates_uniqueness_of :username

    has_attached_file :avatar, styles: { large: "800x800>", medium: "300x300>", thumb: "50x50>" }, default_url: "/assets/missing-user.png"
    validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/

    after_update :create_avatar_post, if: :avatar_changed?

    def create_avatar_post
            description: "#{username} update their profile picture",
            user_id: id
            # Whatever other attributes of Post
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download