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
的'find'方法通過ID找到一個記錄 - 該方法不會返回一個集合,這就是爲什麼'each'沒有定義。如果您想要返回一個品牌的優惠券集合,請參閱我的答案。 – 2015-02-09 00:07:08
謝謝@JordanDedels – 2015-02-09 00:14:36