title: Rails Sort/Group by dynamic field
body: <p>I'm working on a rails app that is passing serialized values in a JSON dump to the client. I need the requirements to be sorted in a specific order, with objects that contain equal "deadline_dates" to be grouped together. That field is dynamic and many of my objects don't contain that field at all.</p>
  
  <p>Here is what my model looks like:</p>
  
  <pre><code>#------ app/models/program_requirement.rb ------#
  class ProgramRequirement &lt; ActiveRecord::Base
   include HasFields
  
   belongs_to :program
   has_many :responses
   has_many :applications, through: :responses
  
   store_accessor :fields, :deadline_date
  end
  </code></pre>
  
  <p>Here is the method I'm using to pass the objects into my serializer:</p>
  
  <pre><code>#------ app/models/program.rb ------#
  def sorted_program_requirements
  self.program_requirements.sort_by{|a| [a.deadline, a.position]}.map {
    |requirement| ProgramRequirementSerializer.new(requirement, root: false) }
  end
  </code></pre>
  
  <p>The sorting for the "deadline" and "position" values works fine, but some reason, I'm unable to sort by including a param into my sort_by method such as:</p>
  
  <pre><code>a.fields[:deadline_date]
  </code></pre>
  
  <p>I've attempted using group_by, but that also doesn't seem to do what I'd expect. I just want to group requirements by equal deadline_dates if they exist, and then sort the rest by the other two static fields.</p>
  
  <p>Any help is appreciated!</p>
  
  <h3>UPDATE</h3>
  
  <p>Output from: program_requirements.each { |pr| p pr.fields[:deadline_date] }</p>
  
  <pre><code>[#&lt;ProgramRequirement:0x007fb198a12d58
    id: 126,
    program_id: 1159,
    title: "Req",
    deadline: "manual",
    position: 1,
    fields: {"deadline_date"=&gt;"2015-09-16"}
   #&lt;ProgramRequirement:0x007fb198a12bf0
    id: 127,
    program_id: 1159,
    title: "Req",
    deadline: "initial",
    position: 2,
    fields: {}
   #&lt;ProgramRequirement:0x007fb198a12a60
    id: 132,
    program_id: 1159,
    title: "Req",
    deadline: "precampaign",
    position: 3,
    fields: {}
   #&lt;ProgramRequirement:0x007fb198a128d0
    id: 133,
    program_id: 1159,
    title: "t444",
    description: nil,
    deadline: "manual",
    position: 4,
    fields: {"deadline_date"=&gt;"2015-09-16"}
  ]
  </code></pre>