2015-02-08 73 views
0

我有2个模型:品牌和优惠券,优惠券嵌套在品牌中。在优惠券的索引页面上,我想显示所有优惠券和当前品牌ID。上/品牌/ 1 /优惠券Rails:在控制器中使用嵌套资源筛选索引结果

实例 - 要显示所有品牌标识的消费券将品牌/ 1 /优惠券时= 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 

错误,我得到。 ..

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 
+0

的'find'方法通过ID找到一个记录 - 该方法不会返回一个集合,这就是为什么'each'没有定义。如果您想要返回一个品牌的优惠券集合,请参阅我的答案。 – 2015-02-09 00:07:08

+0

谢谢@JordanDedels – 2015-02-09 00:14:36

回答

1

假设你的航线设置正确,这应该工作:

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

配置/ routes.rb中

resources :brands do 
    resources :coupons 
end 
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