相关疑难解决方法(0)

使用 Rails 包括对儿童的条件

我有一个Parent有很多孩子的模型Child。我想获得所有父模型并显示每个父模型Childincludes据我所知,这是 Rails方法的经典用例。

但是,我无法让 Rails 在不将父模型限制为有子模型的情况下向子模型添加条件。

例如,这仅输出有孩子的父母:

Parent.includes(:children).where(children: {age: 10}).each do |parent|
  # output parent info
  parent.children.where("age = 10").each do |child|
   #output child info
  end
end
Run Code Online (Sandbox Code Playgroud)

我已经查看了Rails 包含条件,但似乎我遇到了与问题的 OP 相同的问题,并且接受的答案的任何部分都不能解决它(它要么只有一些父项,要么求助于多个查询) .

ruby-on-rails rails-activerecord

5
推荐指数
1
解决办法
8011
查看次数

Ruby 包含范围

在我的 Rails 6 应用程序中,我有定义active范围的模型 Journey:

class Journey < ApplicationRecord
  has_many :users, through: :journey_progresses
  has_many :journey_progresses, dependent: :destroy

  scope :active, -> { where(is_deleted: false) }
end
Run Code Online (Sandbox Code Playgroud)

在我的端点中,我想显示用户旅程进度以及序列化器旅程本身。为此,我使用下面的查询,效果很好

      def query
        current_user.journey_progresses.includes(:journey)
      end
Run Code Online (Sandbox Code Playgroud)

如何修改上述查询以仅显示活动旅程?我试图添加类似的位置current_user.journey_progresses.includes(:journey).where(is_deleted: false),但出现错误:

Caused by PG::UndefinedColumn: ERROR:  column journey_progresses.is_deleted does not exist
Run Code Online (Sandbox Code Playgroud)

根据我尝试过的这个答案current_user.journey_progresses.includes(:journey).where(journey: {is_deleted: false} ),但我收到另一个错误:

Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "journey"
Run Code Online (Sandbox Code Playgroud)

此类操作的正确语法是什么?

ruby ruby-on-rails

3
推荐指数
1
解决办法
1804
查看次数

在 ActiveRecord 中包含 with where 子句

我想预加载关联,但如果不存在关联,我想返回主要关系。

要理解我的问题,这里有一个可重现的脚本:

# frozen_string_literal: true
gem 'rails'
require 'active_record'

puts "Active Record #{ActiveRecord::VERSION::STRING}"

ActiveRecord::Base.establish_connection(
  adapter: 'sqlite3',
  database: ':memory:'
)

ActiveRecord::Schema.define do
  create_table :organisations, force: true do |t|
    t.string 'name', limit: 255, null: false
    t.datetime 'created_at'
    t.datetime 'updated_at'
  end

  create_table :groups, force: true do |t|
    t.string 'name', limit: 255, null: false
    t.integer 'shop_id', null: false
    t.datetime 'created_at'
    t.datetime 'updated_at'
  end

  create_table :groups_organisations, force: true do |t|
    t.integer  'organisation_id', null: false
    t.integer  'group_id', null: false
    t.datetime 'created_at'
    t.datetime 'updated_at'
  end
end

class …
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails

2
推荐指数
1
解决办法
6506
查看次数