Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.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 在GET response JSON中插入另一个字段_Ruby On Rails_Json - Fatal编程技术网

Ruby on rails 在GET response JSON中插入另一个字段

Ruby on rails 在GET response JSON中插入另一个字段,ruby-on-rails,json,Ruby On Rails,Json,我有以下代码响应GET/something.json: def index @something = Something.all respond_to do |format| format.json { render json: @something } end end 它在数据库中运行一个SELECT*FROM something,将结果格式化为JSON,并用它进行响应 请求可能通过查询参数请求另一个字段,该参数位于与something不同的表中。通过执行以下操作,我成

我有以下代码响应
GET/something.json

def index
  @something = Something.all

  respond_to do |format|
    format.json { render json: @something }
  end
end
它在数据库中运行一个
SELECT*FROM something
,将结果格式化为JSON,并用它进行响应

请求可能通过查询参数请求另一个字段,该参数位于与
something
不同的表中。通过执行以下操作,我成功检索了所需字段:

def index
  @something = Something.all

  if params[:get_field_from_some_other_table] == "true"
    @something.each do |i|
        some_other_table = SomeOtherTable.find(i.some_other_table_id)
        the_field_i_want = some_other_table.the_field
    end
  end

  respond_to do |format|
    format.json { render json: @something }
  end
end

但我还没有找到将字段添加到JSON字符串的方法。我该怎么做?或者有没有更好的方法通过
连接
或类似的方式检索包含
某物
表内容的字段?

某物
其他表
应该以某种方式与活动记录相关。。。也许一个
有一个

试试看,然后使用
@something.all.includes(:other\u table\u属性)


除此之外,请用一些可读的示例适当地发布您的代码,这非常有帮助,并且会给您更快的响应:)

您试图做的事情非常不清楚,如果您提出您试图解决的实际问题,而不是任何极为抽象的版本,这可能会有所帮助。