开发者

How do I search for all users in my db that return true on a custom method I wrote? - Rails3

开发者 https://www.devze.com 2023-03-19 08:11 出处:网络
This is my User object and its attributes: ruby-1.9.2-p0 > User => User(id: integer, email: string, encrypted_password: string, password_salt: string, reset_password_token: string, remember_to

This is my User object and its attributes:

ruby-1.9.2-p0 > User
 => User(id: integer, email: string, encrypted_password: string, password_salt: string, reset_password_token: string, remember_token: string, remember_created_at: datetime, sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: datetime, current_sign_in_ip: string, last_sign_in_ip: string, username: string, first_name: string, last_name: string, created_at: datetime, u开发者_如何学JAVApdated_at: datetime, invitation_token: string, invitation_sent_at: datetime, plan_id: integer, current_state: string, confirmation_token: string, confirmed_at: datetime, confirmation_sent_at: datetime, space_used: integer, failed_attempts: integer, unlock_token: string, locked_at: datetime, trial_end_date: date, active_subscription: boolean) 

The custom method that is defined in my User.rb model is:

def trial_will_almost_end?
  if (self.trial_end_date - Date.today <= 3)
    return true
  else
    return false
  end
end

So basically what I want to do is to search for all Users that have a trial_will_almost_end returning true.

I will also want to search for all users that return true for this method:

def has_trial_expired?
   if (self.trial_end_date <= Date.today)
    return true
   else
    return false
   end
end

This is all to be done in Rails 3 ofcourse.

Thanks.


ActiveRecord is a database query interface, so essentially every method gets broken down into SQL at the end. In your case, you want to execute a ruby function in the database, which is impossible unless you fetch the records and then loop over them separately.

You could however fetch your records using sql "where" clause(note: possibly not the right/most efficient syntax):

User.find :all, :conditions => ["TO_DAYS(trial_end_date) - TO_DAYS(NOW()) <= 3"]
0

精彩评论

暂无评论...
验证码 换一张
取 消