活动记录在自身内部哈希

时间:2011-07-15 11:11:24

标签: ruby-on-rails ruby http activerecord hash

所以这有点愚蠢,缺乏编程知识,而不是ruby或rails特定的东西。

如果我想将一个普通的类变成哈希,那就不那么糟了。我已经有一个:

class CustomRequest
  require 'json'
  require 'net/http'
  attr_accessor :url, :depth, :status

  def initialize(url,depth)
    @url = url
    @depth = depth
  end

  def make_me_hash_and_send

    @myReq = {:url => @url, :depth =>@depth}
    myJsonReq = @myReq
    puts myJsonReq

    res = Net::HTTP.post_form(URI.parse('http://127.0.0.1:3008/user_requests/add.json'),
    myJsonReq)

  end
end

只需从构造函数中传递的内部变量生成哈希。我想对积极的记录做同样的事情,但它的抽象性并不容易。

让我说我有这个班级

def  turn_my_insides_to_hash
#How do I take the actual record variables 
# nd generate a hash from them.
#Is it something like

@myHash = {:myString = self.myString
  :myInt => self.myInt }

end

我可能会以错误的方式看待这个问题。我知道在课堂外我可以简单地说

@x = Result.find(passed_id).to_hash

然后做我想做的事。但我宁愿打电话给某事

@x = Result.send

(将结果的变量转换为哈希并发送它们) 我已经有了发送部分,只需要知道如何从类内部将变量转换为哈希。

2 个答案:

答案 0 :(得分:5)

您可以尝试使用JSON而不是YAML:

Result.find(passed_id).to_json

Result.find(passed_id).attributes.to_json

您也可以使用以下选项:except和:仅用于to_json方法。

Result.find(passed_id).attributes.to_json(:only => ['status', 'message'])

答案 1 :(得分:3)

record.serializable_hash

http://api.rubyonrails.org/v4.0.12/classes/ActiveModel/Serialization.html#method-i-serializable_hash

我写了更多东西,因为我要求我这样做。

相关问题