我整天都在努力解決這個問題,但沒有得到任何結果。我有這4個模型。Shop Customer Credit和CreditChange
我想CreditChanges為商店的顧客退貨,而不是顧客。像這樣:
latest_changes = Shop.last.customers.credit_changes
我試圖join喜歡這個,但它回傳的是客戶而不是credit_changes
Shop.last.customers.joins(:credit, :credit_change).where.not(credit_changes: {date: nil})
我的模型如下所示:
class Shop < ActiveRecord::Base
has_many :customers, dependent: :destroy
class Customer < ActiveRecord::Base
has_one :credit, dependent: :destroy
has_many :credit_changes, through: :credit
belongs_to :shop
class Credit < ActiveRecord::Base
belongs_to :customer
has_many :credit_changes, dependent: :destroy
class CreditChange < ActiveRecord::Base
belongs_to :credit
我哪里做錯了?
uj5u.com熱心網友回復:
嘗試顛倒你看待事物的方式:
CreditChange.joins(:credit => :customer).where(customers: {shop: Shop.last}).where.not(credit_changes: {date: nil})
uj5u.com熱心網友回復:
你想要一個有很多的關系。
商店通過其客戶有許多 CreditChanges。
嘗試:
class Shop
has_many :customers
has_many :credit_changes, through: :customers
end
@shop.credit_changes
您可以在 Rails 檔案中閱讀更多內容 https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/447706.html
