我有3個型號,Shop
Mall
和Sale
。 a Mall
has_many Shops
,Shop
belongs_to a Mall
and has_many Sales
,and Sale
belongs_to a Shop
。我想要做的是,當我去特定商城的show
頁面時,我想讓它只屬於屬於該特定商場的商店的銷售額顯示在該頁面上(商場展示頁面)。於是,我嘗試過許多不同的方式在商場的控制器的表演動作要做到這一點,但我不斷收到此錯誤:如何使用相關模型的特定ID加載記錄 - 導軌4
undefined method 'sales' for nil:NilClass
這是我現在商場控制器:
class MallsController < ApplicationController
before_action :set_mall, only: [:show, :edit, :update, :destroy]
# GET /malls/1
# GET /malls/1.json
def show
@shops = @mall.shops.all
@sales = @shop.sales.where('offer_end >= ?', Date.today).order('discount_to DESC')
end
private
# Use callbacks to share common setup or constraints between actions.
def set_mall
@mall = Mall.find(params[:id])
end
end
shop.rb:
class Shop < ActiveRecord::Base
has_many :categorizations
has_many :categories, :through => :categorizations
has_many :mall_shops
has_many :malls, :through => :mall_shops
has_many :sales, dependent: :destroy
validates :name, presence: true, uniqueness: true
end
mall.rb
class Mall < ActiveRecord::Base
has_many :mall_shops
has_many :shops, :through => :mall_shops
validates :name, presence: true, uniqueness: true
end
sale.rb:
class Sale < ActiveRecord::Base
belongs_to :shop
end
mall_shop.rb
class MallShop < ActiveRecord::Base
belongs_to :shop
belongs_to :mall
end
通過你的模型重新看完後,我看你有'mall_shops'。這張桌子是什麼樣的? –
問題是你沒有定義'@ shop',所以是錯誤。 – Pavan
@JustinLicata我更新了包含mall_shop的問題。 max給出的答案解決了我的問題,但是如果您有其他解決方案,請隨時分享。 –