我正在学习编程,并且正在尝试使用Ruby。我想限制一种功能,该功能允许用户向我发送介绍请求(每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
您接近。不过,您需要进行时间比较,并且方法(假设它在模型中)应该是类方法或范围。
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