我正在学习编程,并且正在尝试使用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
答案 0 :(得分:0)
您已经关闭。但是,您需要进行时间比较,并且该方法(假设它在模型中)应该是类方法或范围。
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO Auto-generated method stub
User user = this.userDao.getByUsername(username);
if (user == null) {
System.out.println("User not found! " + username);
throw new UsernameNotFoundException("User " + username + " was not found in the database");
}
System.out.println("Found User: " + user);
String role = user.getUser_role();
List<GrantedAuthority> grantList = new ArrayList<GrantedAuthority>();
if (role != null) {
GrantedAuthority ga = new SimpleGrantedAuthority(role);
grantList.add(ga);
}
UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(),
user.getEncrypted_password(), grantList);
return userDetails;
}
}
然后在控制器中,您可以检查最近发出了多少个请求。
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