【问题标题】:Rails 5.0.0.1, ActiveRecord includes with select and has_many throughRails 5.0.0.1,ActiveRecord 包括通过 select 和 has_many
【发布时间】:2016-12-12 02:44:31
【问题描述】:

我正在使用这行代码来生成我的表格:

def index
  @documentation_languages = Documentation::Language
    .includes(:tags)
    .select(:id, :abbreviation, :name, :version)
    .order(:slug)
end

他们会打电话给:

SELECT "documentation_languages"."id", "documentation_languages"."abbreviation", "documentation_languages"."name", "documentation_languages"."version" FROM "documentation_languages" ORDER BY "documentation_languages"."slug" ASC
SELECT "documentation_language_tags".* FROM "documentation_language_tags" WHERE "documentation_language_tags"."language_id" IN (2, 3, 1, 4, 5, 6, 7, 8, 9, 10, 11, 13, 12, 14, 15, 16, 17)
SELECT "documentation_tags".* FROM "documentation_tags" WHERE "documentation_tags"."id" = 1

我在Documentation::Language 模型中使用has_many :tags, through: :language_tags。我可以从包含的tags 表中选择诸如documentation_tags.name 之类的任何方式吗?

【问题讨论】:

    标签: activerecord ruby-on-rails-5


    【解决方案1】:

    我通过使用has_manyscope 参数解决了这个问题,并将代码更改为:

    has_many :tags, ->{ select(:name) }, through: :language_tags
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多