lundi 26 mars 2018

Join tables with Ruby on Rails 5

I have models Article and Language (tables articles and languages). Article has_many languages and Language belongs_to article. I want to select articles with their languages. I am using this in Article model:

def self.articles_per_page(limit, offset)
  joins("LEFT JOIN languages ON languages.article_id = articles.id")
  .select('articles.id, languages.language, COUNT(languages.id) as all_languages')
  .limit(limit).offset(offset)
  .group('articles.id, languages.language')
end

In the articles_controller:

def get_per_page
  limit = 40
  render json: Article.articles_per_page(limit, params[:offset])
end

Then I make Ajax request to get JSON response with articles and their languages:

$.get(articlesUrl + '?offset=' + offset, function(article){
    $.each(article, function(index, performance){
        $('#articleTable').append(// DATA //);
    });
            offset = $('#articleTable').children('.articleRow').length;
        })

The problem is that, if I have 1 article in articles table and for the example 3 languages associated with this article in the languages table, it returns 3 rows with same article.

Aucun commentaire:

Enregistrer un commentaire