-1

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?

EGGo
  • 1
  • If you are a beginner the best way to do this if yourself. The internet is filled with useful resources to help you with the task. Relying one someone to write this for you, won't get you very far. https://stackoverflow.com/questions/20188047/rails-respond-to-json-and-html should get you started. – razvans Oct 20 '21 at 09:46
  • Please provide enough code so others can better understand or reproduce the problem. – Community Oct 20 '21 at 10:05

1 Answers1

0

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.

Emilien Baudet
  • 428
  • 4
  • 10