我有一个json文件,我想在我的devices / index.html.erb中包含json数据。我将json文件保存在assets / javascript /文件夹中。我也使用scaffold生成了我的设备视图和控制器。 。我的json文件是。所以我想知道如何将这个文件包含在我的rails应用程序中
{"records":[
{"id":"1","gdname":"Amaresh","fdname":"Rahul","adname":"Satish","sdname":"Santosh","pdname":"Jitendra"},
{"id":"2","gdname":"Amaresh","fdname":"Rahul","adname":"Satish","sdname":"Santosh","pdname":"Jitendra"},
{"id":"3","gdname":"Amaresh","fdname":"Rahul","adname":"Satish","sdname":"Santosh","pdname":"Jitendra"},
{"id":"4","gdname":"Amaresh","fdname":"Rahul","adname":"Satish","sdname":"Santosh","pdname":"Jitendra"}
]}
index.html.erb
def index
@dealers = JSON.parse(File.read(File.join('assets/javascript', 'dealer.json')))
@dealers = Dealer.all
end
答案 0 :(得分:0)
是否正在阅读文件?
# devices_controller.rb
def index
@data = JSON.parse(File.read(File.join('assets/javascript/folder', 'myjson.json')))
...
end
您将把它用作您可以在视图中使用的ruby变量。
更新
# inside devices_controller.rb
def index
# place the file under public folder
@dealers = JSON.parse(File.read(File.join('public','dealers.json')
...
end
# inside devices/index.html.erb
...
<p><%= @dealers['records']['id'] %></p>
...