我正在构建一个调用跟踪应用程序,作为学习 Rails 和 twilio 的一种方式。
现在,我有模型方案计划 has_many users has_many Phones。
在计划模型中,我有一个名为 max_phone_numbers 的参数。
我想要做的是根据计划提供的 max_phone_numbers 来限制用户拥有的电话数量。
流程看起来像这样:
1) 用户购买一堆电话号码 2)当User.phones.count = max_phonenumbers时,购买更多电话号码的功能被禁用,并且会弹出一个链接到upgrade_path
我不太确定我会如何去做这件事。我需要在模型和 Controller 中执行哪些操作组合?
我将在 Controller 中定义什么,以便在 View 中可以扭曲按钮周围的 if/then 语句?
即如果达到限制,则显示此内容,否则显示按钮
我应该在我的模型中添加什么来防止某人直接访问该链接?
任何关于做类似事情的指导或资源将不胜感激
这是我当前的用户模型
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# password_digest :string(255)
# remember_token :string(255)
# twilio_account_sid :string(255)
# twilio_auth_token :string(255)
# plan_id :integer
# stripe_customer_token :string(255)
#
# Twilio authentication credentials
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation, :plan_id, :stripe_card_token
has_secure_password
belongs_to :plan
has_many :phones, dependent: :destroy
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: true
validates :password, presence: true, length: { minimum: 6 }, on: :create
validates :password_confirmation, presence: true, on: :create
validates_presence_of :plan_id
attr_accessor :stripe_card_token
def save_with_payment
if valid?
customer = Stripe::Customer.create(description: email, plan: plan_id, card: stripe_card_token)
self.stripe_customer_token = customer.id
save!
end
rescue Stripe::InvalidRequestError => e
logger.error "Stripe error while creating customer: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end
def create_twilio_subaccount
@client = Twilio::REST::Client.new(TWILIO_PARENT_ACCOUNT_SID, TWILIO_PARENT_ACCOUNT_TOKEN)
@subaccount = @client.accounts.create({:FriendlyName => self[:email]})
self.twilio_account_sid = @subaccount.sid
self.twilio_auth_token = @subaccount.auth_token
save!
end
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
最佳答案
您可以向您的手机型号添加自定义验证,以检查用户是否已达到其限制。如果用户达到限制,这将阻止创建任何新手机。
在您的 User 类中
def at_max_phone_limit?
self.phones.count >= self.plan.max_phone_numbers
end
在您的电话类(class)中
validate :check_phone_limit, :on => :create
def check_phone_limit
if User.find(self.user_id).at_max_phone_limit?
self.errors[:base] << "Cannot add any more phones"
end
end
在你的 View /表单中,你会做这样的事情
<% if @user.at_max_phone_limit? %>
<%= link_to "Upgrade your Plan", upgrade_plan_path %>
<% else %>
# Render form/widget/control for adding a phone number
<% end %>
关于ruby-on-rails - 根据参数限制用户的列行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12775678/