mardi 27 mars 2018

Select from foreign table with join and output JSON - Ruby on Rails 5

I have models Article and Language. Article has_many :languages and Language belongs_to: :article. I have method for selecting articles with their languages in Article model:

def self.per_page(limit, offset)
  left_joins(:languages)
  .limit(limit).offset(offset)
  .select('articles.id, articles.title, languages.language')
  .group(:id)
end

I call this method in articles_controller.rb:

def index
  limit = 40
  @articles = Article.per_page(limit, params[:offset])
  byebug
  render json: @articles
end

I have in articles one row with id=105 and three rows in languages table with article_id=105 The problem is that it selects only the first row per related article in languages table, but not all. Now JSON looks like:

{
    id: 105
    title: 'Some title',
    language: 'English'
}

I want to select all articles with all related to them languages and JSON output to be like :

{
    id: 105
    title: 'Some title',
    language: ['English', 'French', ...]
}

How can I do that ? It is not a problem if it is more than one request in the controller.

Aucun commentaire:

Enregistrer un commentaire