0

我有一个Payment,ClientPaymentTransactions模型。我试图显示PaymentTransactions给定的所有内容,Client但控制器返回一个空数组。

我用来到达那里的路线是/api/v1/clients/:id/payment_transactions

这是我的路线文件:

Rails.application.routes.draw do
  namespace :api, defaults: { format: :json } do
    namespace :v1 do
      resources :payments, only: [ :index ]
      resources :clients, only: [ :index ]

      resources :clients, only: [:show] do
        resources :payment_transactions, only: [:index]
      end
    end
  end
end

铁路路线:

Uri Pattern /api/v1/clients/:client_id/payment_transactions
Controller#Action api/v1/payment_transactions#index {:format=>:json}

这些是我的模型:

class Payment < ApplicationRecord
  belongs_to :client, optional: true, dependent: :destroy
  has_many :payment_transactions, dependent: :destroy
end

class Client < ApplicationRecord
  has_one :payment, dependent: :destroy
  has_many :payment_transactions, through: :payment, dependent: :destroy
end

class PaymentTransaction < ApplicationRecord
  belongs_to :payment, optional: true
  has_one :client, through: :payment
end

这是我的控制器:

class Api::V1::PaymentTransactionsController < Api::V1::BaseController
  before_action :set_client

  def index
    @transactions = PaymentTransaction.where(client: @client)
  end

  private

  def set_client
    @client = Client.find(params[:client_id])
  end
end

我可以做PaymentTransaction.client并获得与该 PaymentTransaction 关联的客户端。我也可以Client.payment_transactions为给定的客户获取所有交易。

但是,调用/api/v1/clients/1/payment_transactions返回[]

编辑:

控制器动作的改变@transactions = PaymentTransaction.where(client_id: @client.id)导致

ActionView::Template::Error (PG::UndefinedColumn: ERROR:  column payment_transactions.client_id does not exist
LINE 1: ...transactions".* FROM "payment_transactions" WHERE "payment_t...
                                                             ^
):
    1: json.array! @transactions do |transaction|
    2:   json.extract! transaction, :id, :payment_id, :transaction_identification, :amount, :status
    3: end
4

1 回答 1

1

ActiveRecord 的where方法期望其输入是被调用模型上的列,因此您不能使用它来按中间关联进行过滤。相反,您可以payment_transaction直接从@client对象调用定义的关联。

  def index
    @transactions = @client.payment_transactions
  end

旁注:
直接使用关联还有一个额外的优势,即允许您稍后立即加载记录,以防您需要在他们的支付交易旁边列出客户。例如

Client.all.includes(:payment_transactions)

使用 awhere不会使这很容易实现。

于 2021-03-18T03:50:45.097 回答