Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.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/python-2.7/5.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:更改json输出_Ruby On Rails_Json_Ruby - Fatal编程技术网

Ruby on rails Rails:更改json输出

Ruby on rails Rails:更改json输出,ruby-on-rails,json,ruby,Ruby On Rails,Json,Ruby,下面是代码renderjson:news,:include=>{:tags=>{:only=>:name},:category=>{:only=>:name},它输出以下内容: { "id": 2, "title": "title", "tags": [], "category": { "name": "lorem" } 有没有办法像这样输出它 { "id": 2, "title": "title", "tags": [], "category": "lorem" # <--- di

下面是代码
renderjson:news,:include=>{:tags=>{:only=>:name},:category=>{:only=>:name}
,它输出以下内容:

{
"id": 2,
"title": "title",
"tags": [],
"category": {
  "name": "lorem"
}
有没有办法像这样输出它

{
"id": 2,
"title": "title",
"tags": [],
"category": "lorem" # <--- display category name 
}
{
“id”:2,
“头衔”:“头衔”,
“标签”:[],

“类别”:“lorem”#在您的新闻模型中,您可以定义:

def as_json(options={})
  {id: id, title: title, tags: tags}.tap do |hash|
    hash[:category] = category.name unless category.nil?
  end
end
然后简单地:
render json:news


您可能需要更改as_json中的代码,以匹配您为模型创建的任何结构,但想法是使用您想要的json格式创建一个哈希,然后让rails将其转换为json。

您使用的是序列化库吗?您能在您的帖子中包含这方面的详细信息吗?现在我得到了
未定义的方法
nil:NilClass`的名称',因为并不是所有新闻都分配了类别。有什么办法可以解决这个问题吗?你能从db/schema.rb发布新闻模型的表项吗?我不能在不了解其内部结构的情况下为你的新闻类编写工作函数。哦,等一下,我刚刚看到你的评论。我会更新我的代码。