如何通过控制器从模型更新对象的属性

时间:2018-03-13 16:40:17

标签: ruby-on-rails

我一直在努力关注其他答案和文档以获得一个非常简单的问题。

我理解' skinny'控制器和'胖模型'概念。但是,我真的很难在控制器和模型之间传递数据。

例如,我只想在调用操作时更新属性。

 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

这显然看起来很糟糕,因为模型应该有权访问数据库来更改属性。这是如何完成的,因为我无法将此实例变量传递到模型中。它不是同一个&#39;实例&#39;就像它在控制器中一样。

例如,

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

这不会奏效。我有什么选择?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

# 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