Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails控制器散列到数组中_Ruby On Rails - Fatal编程技术网

Ruby on rails Rails控制器散列到数组中

Ruby on rails Rails控制器散列到数组中,ruby-on-rails,Ruby On Rails,尝试使用序列化程序更改JSON响应的结构。但是,我遇到了一些问题,因为我需要按字母顺序对数据进行分组(|one_record | one_record.name[0]。to_s),此时返回的是散列。如何将其转换为可以传递到序列化程序中的数组 #WIP - order should return an array of contacts ordered alphabetically according to their name. def order # retur

尝试使用序列化程序更改JSON响应的结构。但是,我遇到了一些问题,因为我需要按字母顺序对数据进行分组(
|one_record | one_record.name[0]。to_s
),此时返回的是散列。如何将其转换为可以传递到序列化程序中的数组

    #WIP - order should return an array of contacts ordered alphabetically according to their name.
    def order
        # returns the first letter of the name
        @ordered_contacts = @user.all_contacts.group_by { |one_record| one_record.name[0].to_s }
        render json: @ordered_contacts, serializer: ContactshipsSerializer, :status => :ok
    end
序列化程序:

class ContactshipsSerializer < ActiveModel::Serializer

  # method override
  def serializable_object(options={})
    @ordered_contacts.map do | *title*, ordered_contacts |
      [ *title* , serialized_ordered_contacts(ordered_contacts) ]
  end.to_h
  end

  private

    def serialized_contactships contactships
      ordered_contact.map{ |contactship| ContactshipsSerializer.new(ordered_contact, root: false) }
    end
end
class ContactshipsSerializer
如果您只是在寻找一个数组,
@user.all_contacts.group_by{one_record}one_record.name[0].to_}.to_a
就可以了。但是
contactshipserializer
如何期望数据呢?嘿,这很有道理。我写这个问题时假设错误来自于提交散列(序列化程序和JSON格式的新功能),但我似乎错了。已更新问题以包含序列化程序,但标题/组键有误?如果您仅使用其名称的第一个字母来组织它们,这将不能保证它们按字母顺序排序。有什么方法可以做到这一点吗?这个问题更多的是关于重新构造JSON,这样我就可以将它传递给React Native,但如果您只是在寻找数组,
@user.all_contacts.group_by{one_record{124; one_record}one_record.name[0]。to_s}。to_a
将起到作用。但是
contactshipserializer
如何期望数据呢?嘿,这很有道理。我写这个问题时假设错误来自于提交散列(序列化程序和JSON格式的新功能),但我似乎错了。已更新问题以包含序列化程序,但标题/组键有误?如果您仅使用其名称的第一个字母来组织它们,这将不能保证它们按字母顺序排序。有什么方法可以做到这一点吗?这个问题更多的是关于重新构造JSON,这样我就可以将其传递给React Native,但最好知道如何按字母顺序排序