Rails: 在控制器中使用嵌套资源过滤索引结果

Rails: Filter index results with nested resource in controller

我有 2 个模型:品牌和优惠券,优惠券嵌套在品牌中。在优惠券的索引页面上,我想显示所有具有当前品牌 ID 的优惠券。

/brand/1/coupons 上的示例 - 想要显示品牌 ID = 1 的所有优惠券

代码如下

create_table "brands", force: true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "logo"
end

create_table "coupons", force: true do |t|
  t.integer  "brand_id",   limit: 255
  t.string   "code"
  t.date     "expiry"
  t.string   "link"
  t.string   "details"
  t.datetime "created_at"
  t.datetime "updated_at"
end

class Brand < ActiveRecord::Base
    has_many :coupons
    accepts_nested_attributes_for :coupons
end

class Coupon < ActiveRecord::Base
   belongs_to :brand
end

class CouponsController < ApplicationController
before_action :set_coupon, only: [:show, :edit, :update, :destroy]

def index
    @coupons = Coupon.find(params[:brand_id]
end

end

我在前往 brands/1/coupons 时遇到错误 ...

NoMethodError in CouponsController#index
undefined method `each' for #<Coupon:0x000001068e8f58>


  else
    match = match_attribute_method?(method.to_s)
    match ? attribute_missing(match, *args, &block) : super
  end
end

假设您的路线设置正确,这应该有效:

@coupons = Coupon.where(brand_id: params[:brand_id])

config/routes.rb

resources :brands do
  resources :coupons
end

在控制器中

@coupons = Coupon.all
or
@coupons = Coupon.where(brand_id: params[:id])

可见

@coupons.each do |coupon|
  coupon.brand_id
  or 
  coupon.brand.id  # but in this case your will have N+1 problem