complete beginner here. I'm following the Rails tutorial on their website so I just created a basic app with Posts and Comments.
I would like to create an action in ArticlesController which returns the list of articles as JSON. Could you help me?
complete beginner here. I'm following the Rails tutorial on their website so I just created a basic app with Posts and Comments.
I would like to create an action in ArticlesController which returns the list of articles as JSON. Could you help me?
You can do it like this :
# app/models/article.rb
class Article < ApplicationRecord
# if you want to specify which informations you want to share on your json
def as_json(option = nil)
super(only: %i[id name content])
end
end
# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def index
@articles = Article.all
respond_to do |format|
format.json {render json: @articles}
end
end
end
You can also take a look to the jbuilder gem to help you to format your json as you want.