从外国桌子中选择带有连接和输出JSON -RUBY在Rails 5上



我有型号ArticleLanguageArticle has_many :languagesLanguage belongs_to: :article。我有在Article模型中选择具有其语言的文章的方法:

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

我在articles_controller.rb中调用此方法:

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

我在articles中有id=105的一行,而languages表中有三行,带有article_id=105问题在于,它在语言表中仅选择每个相关文章的第一行,但不是全部。现在JSON看起来像:

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

我想选择所有与它们的语言和JSON输出相关的文章,例如:

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

我该怎么做?如果控制器中的请求超过一个请求,那不是问题。

听起来您的关联未正确定义。如果将belongs_to关联添加到Language模型中,语言只能属于单个文章。

相反,您想要这样的东西:

class Article < ApplicationRecord
  has_many :translations
  has_many :languages, through: :translations
end
class Translation < ApplicationRecord
  belongs_to :article
  belongs_to :language
end
class Language < ApplicationRecord
  has_many :translations
  has_many :articles, through: :translations
end

这与translations作为联接表建立了许多一对多的关联。

最新更新