0

Here is my code first

  def participation_earning(partcpnt_usr)
    case show_participant_users
    when Array
      puts "***********Inside Array Statement - #{Time.now} *********"
      sleep 1
      show_participant_users.find do |show_prtcpnt_usr|
        show_prtcpnt_usr.show_participant_id == partcpnt_usr.participant_id
      end
    when ActiveRecord::Relation
      puts "***********Inside Relation Statement - #{Time.now} *********"
      sleep 1
      show_participant_users.where(:show_participant_id => partcpnt_usr.participant_id).first
    else
      puts "Will always go in else part"  
    end  
  end 

Few explanation show_participant_users is a relation object on user something like @user.show_participant_users

Now what bothering me is that even though the class for show_participant_users is an Array it still goes into else block no idea why (just to confirm show_participant_users is not nil it an Array)

on the contrary the below code work as expected

array_fields = []

case array_fields
 when Array
  puts "Ruby Array"
 when Hash
  puts "Ruby Hash"
end

any idea other then if/else statement which I dont want to use because of brevity

Thanking You

4

3 回答 3

1

利用:

case show_participant_users.class

例如:

array_fields = User.where("id > 5").limit(2) #return the array
array_fields.class #gives ActiveRecord::Relation and not Array
于 2013-06-07T11:34:55.847 回答
0

您应该在控制台中打印对象的类和祖先,以确保该类是您所期望的。

从语法上看,它是一个方法调用,所以它可能有意想不到的类。

于 2013-06-07T11:42:47.983 回答
0
def participation_earning(partcpnt_usr) 
 case partcpnt_usr
 when Array
   puts "***********Inside Array Statement - #{Time.now} *********"
   sleep 1
   show_participant_users.find do |show_prtcpnt_usr|
      show_prtcpnt_usr.show_participant_id == partcpnt_usr.participant_id
    end
  when ActiveRecord::Relation
   puts "***********Inside Relation Statement - #{Time.now} *********"
   sleep 1
   show_participant_users.where(:show_participant_id => partcpnt_usr.participant_id).first
  else
    puts "Will always go in else part"  
  end  
end 
于 2013-06-07T13:03:15.970 回答