我有型号Article
和Language
。Article has_many :languages
和Language 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
作为联接表建立了许多一对多的关联。