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

时间:2015-02-08 23:50:57

标签: ruby-on-rails nested controllers

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

/ brand / 1 /优惠券上的示例 - 想要显示品牌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

参加品牌/ 1 /优惠券时出错...

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

2 个答案:

答案 0 :(得分:1)

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

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

<强>配置/ routes.rb中

resources :brands do
  resources :coupons
end

答案 1 :(得分:0)

控制器中的

@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