【发布时间】:2021-09-02 09:40:34
【问题描述】:
我有一个应用程序,用户使用设计进行身份验证,在用户模型中,我在数据库中添加了一个名为 admin 的列,默认值为 false。这样我就设法以管理员身份访问应用程序的某些部分。 我有一个订阅模型,每个用户在经过身份验证后都会默认获得一个免费值。我想要实现的是用户列表中的管理员用户可以从免费切换到高级。这是我拥有的代码,我无法让它工作。
用户模型:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
#Validaciones
validates :nombre, :apellido, presence: true
devise :database_authenticatable, :validatable, password_length: 8..128
#Relaciones
has_many :patients, dependent: :destroy
has_many :articles, dependent: :destroy
has_one :profile, dependent: :destroy
has_one :suscription, dependent: :destroy
#Creación de perfil
after_create :set_profile
def set_profile
self.profile = Profile.create()
end
#Creación de suscripcion
after_create :set_suscription
def set_suscription
self.suscription = Suscription.create()
end
end
订阅模式:
class Suscription < ApplicationRecord
belongs_to :user
enum status: {
free: 0,
premium: 1
}
end
用户控制器:
class UsersController < ApplicationController
def index
@pagy, @users = pagy(User.order(created_at: :asc), items:12)
end
def show
@user = User.find(params[:id])
end
end
Suscriptios 控制器:
class SuscriptionsController < ApplicationController
before_action :set_suscription
def show
end
def edit
end
def update
@suscription = Suscription.find(params[:id]).update_params
redirect_to profile_path
flash[:notice] = "La suscripción ha sido actualizada"
end
private
def set_suscription
@suscription = (current_user.suscription ||= Suscription.create)
end
def suscription_params
params.require(:suscription).permit(:status)
end
end
路线: #更新高级版
patch "suscriptions", to:"suscriptions#update", as: "user_premium"
查看(链接):
<%= link_to 'Update', user_premium_path ,method: :patch %>
【问题讨论】:
标签: ruby-on-rails