【问题标题】:Limit requests that users can send to 3 every 30 days. Ruby on Rails将用户每 30 天可以发送的请求限制为 3 个。 Ruby on Rails
【发布时间】:2020-09-27 12:52:40
【问题描述】:

我正在学习编程,并且正在尝试使用 Ruby on rails。我想限制一项允许用户向我发送介绍请求的功能(每 30 天 3 个介绍请求)。我不确定是否必须先创建一个方法,例如:

def month
  where("created_at <?", Date.today - 30.days))
end

我不知道那个方法是否正确,是否可以将它集成到这段代码中:

def create
  @introduction = CompanyIntroduction.create(intro_params)
  if current_user #Admin can edit the user name and email 
    @introduction.user = current_user
    @introduction.user_name = current_user.full_name
    @introduction.user_email = current_user.email
  end 
  if @introduction.save
    flash[:success] = "Thank you. Your request is being reviewed by TechIreland."
  else
    flash[:error] = @introduction.errors.full_messages
  end
  redirect_back(fallback_location: user_companies_path)
end

【问题讨论】:

    标签: ruby-on-rails function time limit


    【解决方案1】:

    你已经接近了。不过,您可以向后比较时间,并且方法(假设它在您的模型上)应该是类方法或范围。

    scope :in_the_last_month, -> { where('created_at > ?', Date.today - 30.days) }
    # or more elegantly
    scope :in_the_last_month, -> { where(created_at: 30.days.ago..) }
    

    然后在控制器中你可以查看最近有多少请求。

    if CompanyIntroduction.in_the_last_month.count >= 3
      # give some error
    else
      # continue
    end
    

    这段代码很简单,你实际上不需要把它变成一个方法,只需要控制器中的代码就可以了。

    if CompanyIntroduction.where(created_at: 30.days.ago..).count >= 3
    

    【讨论】:

    • 非常感谢您的回答,我正在尝试使用您建议的 if 语句,但我想知道是否有任何方法可以包含仅包含来自当前用户的请求的子句。
    猜你喜欢
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 2021-10-06
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多