[英]How to update attribute of object from model via controller
對於一個非常簡單的問題,我一直在努力遵循其他答案和文檔。
我了解“瘦”控制器和“胖模型”的概念。 但是,我確實很難在控制器和模型之間傳遞數據。
例如,我只想在調用動作時更新屬性。
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
這顯然很糟糕,因為模型應該有權訪問數據庫以更改屬性。 由於我無法將此實例變量傳遞到模型中,因此如何完成此操作。 它與控制器中的“實例”不同。
例如,
class Blog < ApplicationRecord
def self.turn_active
@blog.active = true
end
end
這行不通。 我有什么選擇?
你可以做:
# 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.