【问题标题】:active record to hash inside itself活动记录在其内部散列
【发布时间】:2011-10-06 01:50:44
【问题描述】:

所以这有点傻,更缺乏编程知识,而不是任何 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

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

【问题讨论】:

  • @myHash = self::attributes puts YAML::dump(@myHash)
  • 第一个回答的人,我会标记为正确。我正在引用每个参数,甚至不知道属性存在

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


【解决方案1】:

您可以尝试使用 JSON 代替 YAML:

Result.find(passed_id).to_json

Result.find(passed_id).attributes.to_json

您也可以将 :except 和 :only 等选项用于to_json 方法。

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

【讨论】:

  • 这只是对象的 yaml 转储。我实际上将请求作为 json 传递。这在 URL 中确定为 add.json
  • 您的答案是第一个,但问题已经解决,因此无需打开它。
【解决方案2】:
record.serializable_hash

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 2012-03-03
    • 1970-01-01
    相关资源
    最近更新 更多