How to update attribute of object from model via controller

windsofheaven Source

I've been struggling to follow other answers and documentation for a really simple question.

I understand the 'skinny' controller and 'fat model' concept. However, I am really struggling with passing data between the controller and model.

For example, I simply want to update an attribute when an action is called.

 class BlogsController < ApplicationController


 before_action :find_blog, only: [:show, :edit, :update, :destroy, :active]

   def active
      @blog.active = true
      @blog.save
      Blog.send_subscription_emails
      render template: "/blogs/backend/active"
   end
 end

This obviously looks bad as the model should have access to the database to change the attribute. How is this done as I can't pass this instance variable across into the model. It isn't the same 'instance' as it was in the controller.

For example,

class Blog < ApplicationRecord
  def self.turn_active
      @blog.active = true
  end
end

This won't work. What are my options?

ruby-on-rails

Answers

answered 6 months ago MrYoshiji #1

You can do:

# in blog model
def activate
  update_attributes(active: true)
end

# in controller
def active
  @blog.activate
  Blog.send_subscription_emails
  render template: "/blogs/backend/active"
end

comments powered by Disqus