将静态 JSON 文件解析为 rails 对象

int*_*der 1 ruby json flickr ruby-on-rails ruby-on-rails-4

我正在尝试将根目录中的静态 JSON 文件解析为已经预定义的对象,但我对如何让对象“读取”JSON 文件中的每个属性并将其显示为自己的属性感到困惑。我希望我不会让这更令人困惑它是什么?

我的一些代码:

   class PostsController < ApplicationController
  # before_action :set_post, except: [:index, :show]

  # @@posts = File.read('app/assets/javascripts/flickr_feed.json')
  # @posts = JSON.parse(string)

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
    respond_to do |format|
      format.html
      format.json { render json: @@posts }
      # format.json { render json: @@posts }
    end
  end

  # GET /post/1
  # GET /post/1.json
  def show
    @post = @post.assign_attributes JSON.parse(File.read('app/assets/javascripts/flickr_feed.json'))
    respond_to do |format|
      format.html
      format.json { render json: @post }
    end
  end
  ...
Run Code Online (Sandbox Code Playgroud)

如果我去localhost:3000/posts.json我看到欲望输出..

{
"title": "Recent Uploads tagged potato",
"link": "https://www.flickr.com/photos/tags/potato/",
"description": "",
"modified": "2015-11-21T08:41:44Z",
"generator": "https://www.flickr.com/",
"posts": [ // before was "items":
 {
  "title": "Hokkaido potato with butter",
  "link": "https://www.flickr.com/photos/taking5/22873428920/",
  "media": {"m":"https://farm6.staticflickr.com/5813/22873428920_3cac20cc47_m.jpg"},
  "date_taken": "2015-07-18T08:16:24-08:00",
  "description": " <p><a href=\"https://www.flickr.com/people/taking5/\">Taking5<\/a> posted a photo:<\/p> <p><a href=\"https://www.flickr.com/photos/taking5/22873428920/\" title=\"Hokkaido potato with butter\"><img src=\"https://farm6.staticflickr.com/5813/22873428920_3cac20cc47_m.jpg\" width=\"240\" height=\"180\" alt=\"Hokkaido potato with butter\" /><\/a><\/p> <p>Yummy.<\/p>",
  "published": "2015-11-21T08:41:44Z",
  "author": "nobody@flickr.com (Taking5)",
  "author_id": "58375502@N00",
  "tags": "japan hokkaido potato hakodate morningmarket"
 }
]
}
 ...
Run Code Online (Sandbox Code Playgroud)

但如果我去,posts#index我什么也看不到。我知道我没有正确解析数据,但我对如何做到这一点感到困惑。任何帮助将不胜感激。谢谢

TL; DR:我想解析每个项目从JSON文件,以便能够做到post.titlepost.description

编辑 1:更新代码拼写错误。

编辑 2:更新控制器中的代码

Mar*_*req 5

你可以试试:

@post = Post.new
@post.assign_attributes JSON.parse(File.read('app/assets/javascripts/flickr_feed.json'))
Run Code Online (Sandbox Code Playgroud)

如果使用protected_attributesgem,则使用这种方式设置的属性必须attr_accessible在模型中定义,或者without_protection必须使用参数。

编辑:

def index
  @posts =
    JSON.parse(File.read('app/assets/javascripts/flickr_feed.json'))["posts"].inject([]) do |_posts, post_attrs|
      _posts << Post.new(post_attrs)
    end
  respond_to do |format|
    format.html
    format.json { render json: @posts }
  end
end
Run Code Online (Sandbox Code Playgroud)