简体   繁体   English

从具有连接并输出JSON的外部表中选择-Ruby on Rails 5

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

I have models Article and Language . 我有ArticleLanguage模型。 Article has_many :languages and Language belongs_to: :article . Article has_many :languagesLanguage belongs_to: :article I have method for selecting articles with their languages in Article model: 我有在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

I call this method in articles_controller.rb : 我在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. 我在articles有一行id=105 ,在languages表中有3行,而article_id=105问题是它只在语言表中为每个相关文章选择第一行,而不是全部。 Now JSON looks like: 现在,JSON看起来像:

{
    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 : 我想选择所有与它们有关的语言和JSON输出相关的文章,例如:

{
    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. 如果控制器中有多个请求,这不是问题。

It sounds like your associations are not properly defined. 听起来您的关联定义不正确。 If you add a belongs_to association to the Language model a language can only ever belong to a single article. 如果添加了belongs_to关联的Language模型的语言永远只能属于一个文章。

Instead you want something like this: 相反,您需要这样的东西:

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

This creates a many-to-many association with translations as a join table. 这将创建多对多关联, translations作为连接表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM