Rails to_json属于对象

时间:2016-01-21 01:01:07

标签: ruby-on-rails ruby

我有两种模式:橱柜和工作场所。

class Cabinet < ActiveRecord::Base

  def as_json(options={})
    options.merge!({except: [:created_at, :updated_at]})
    super(options)
  end

end

class Workplace < ActiveRecord::Base
  belongs_to :cabinet

  def as_json(options = {})
    options.merge!(:except => [:created_at, :updated_at, :cabinet_id], include:  :cabinet)
    super(options)
  end

end

当我打电话给Cabinet.first.to_json时,我得到了

{
    id: 1, 
    cabinet: "100"
}

但是当我打电话给Workplace.first.to_json id

{
  name: "first workplace",
  Cabinet: {
           id: 1, 
           cabinet: "100",
           created_at: "#created_at",
           updated_at: "#updated_at"
           }
}

为什么这样?谢谢,抱歉我的英文:)

2 个答案:

答案 0 :(得分:0)

不确定我是否关注您,但是您是否希望从Workplace模型中获取属性,而不是在执行Workplace.first.to_json时获取Cabinet数据?

我认为这是因为你在as_json方法配置中包含了内阁here

您应该将其删除或执行此操作:

Workplace.first.attributes.to_json

如果我遗漏了你的问题,请告诉我。

答案 1 :(得分:0)

假设您的模型<?php include '../connection/connect.php'; include '../dbcon.php'; $stat='lock'; $sqla = "UPDATE student SET status=?"; $qa = $db->prepare($sqla); $qa->execute(array($stat)); //here is the part where I want to store the student who didn't exist in vote_logs $stud = mysql_query(" SELECT st.* FROM student st LEFT JOIN studentvotes sv ON st.idno = sv.idno AND st.syearid = sv.syearid WHERE sv.idno IS NULL AND st.syearid = '$no' AND user_type='3'") or die(mysql_error()); //should I put insert? don't what's next Header ('Location:lock_unlock.php'); ?> 具有Cabinet个属性,而:id, :cabinet, :created_at, :updated_at具有Workplace

现在,如果您尝试触发:id, :name, :cabinet_id, ....,那么它将呈现以下内容:

Cabinet.first.to_json

因为属性属于{ id: 1, cabinet: "100" } 模型。然后,您还添加了这些代码行Cabinet,这就是为什么它只呈现options.merge!({except: [:created_at, :updated_at]})属性。如果您尝试触发:id and :name,那么它将呈现:

Workplace.first.to_json

因为这些{ name: "first workplace", Cabinet: { id: 1, cabinet: "100", created_at: "#created_at", updated_at: "#updated_at" } } 。您包含模型options.merge!(:except => [:created_at, :updated_at, :cabinet_id], include: :cabinet),因此它会自动添加到您的json。

相关问题