I want to retrieve objects based on two attributes - pay_period and
user. I have no problem with this if an exact pay_period and user are
selected. However, I want "All" to be an option for the two fields and
I don't know how to get my code to accept "All" as an option and then
act appropriately. Any help would be appreciated.
I prefer to use the empty string for this purpose rather than an
arbitrary magic value like "All". Then
you don't have to worry about someone having the user id 'all'.
In the view:
<select><option value="">All</option>...</select>
Then:
# Find sessions by user id and pay period.
# +user+: user id, or blank for all users
# +pay_period+: pay period, or blank for all pay periods
define self.find_all_for_user(user, pay_period)
conditions = []
unless user.blank?
conditions.push[user]
conditions.first << 'user_id = '
end
unless pay_period.blank?
conditions.push[pay_period]
conditions.first << 'pay_period_id = '
end
end
conditions.first = conditions.first.join(' AND ')
Session.find(:all, :conditions => conditions)
This is the code I have right now...
controller:
@sessions = Session.find_all_for_user(current_user.id,
params[:pay_period])
model:
def self.find_all_for_user(user, pay_period)
find(:all, :conditions => "user_id = #{user} AND pay_period_id =
#{pay_period}")
Be careful. This code is vulnerable to SQL injection attacks. Most
people prefer this:
find(:all, :conditions => [ 'user_id = ? AND pay_period_id = ?',
user, pay_period_id ])