0

我的主模型中有一个方法,它应该根据设置的参数返回特定的值:

def self.retrieve_profiles( params )

  case params[:view]

    when 'image_only'
      fields = %w{ avatar }

    when 'profile_minimal'
      fields = %w{ avatar username age }

    when 'profile_medium'
      fields = %w{ avatar username age first_name last_name bio relationship_status seeking }

    when 'profile_extended'
      fields = %w{ avatar username age first_name last_name bio relationship_status seeking country city photos }

  end    

  profiles = Profile.that_has_photos
  profiles = profiles.where( :country_id => params['country'] ) unless params['country'].nil?    
  profiles = profiles.order( "RAND()" ).limit( params['count'] )      

  # works fine up to here (returns all fields)

  profiles.each do |a|
    fields.each do |field|
      puts a.eval(field)
    end
  end

  # above block makes it fail (private method `eval' called)

end

我的问题是:如何只返回fieldshash 指定的值?

4

1 回答 1

3

使用send而不是eval. 这段代码应该可以正常工作。

  profiles.each do |a|
    fields.each do |field|
      puts a.send(field)
    end
  end
于 2012-09-27T12:56:30.277 回答