开发者

Nested Resource

开发者 https://www.devze.com 2023-03-26 21:39 出处:网络
I would like to display Brand and Subbrand together on a view page. I am getting an error when I try to declare:

I would like to display Brand and Subbrand together on a view page. I am getting an error when I try to declare:

class BrandsController < ApplicationController

def index
  @brands = Brand.all
  @subbrands = @brands.subbrands #error is coming from this line

Error:

undefined method `subbrands' for #<Array:0x9af1898>

I can't seem to get this working, for the life of me!

I originally posted about my problem in this post: Undefined method

I have tried to put the logic into the controller as above to see if that helps, but I am still getting the error. The details of the models and routing can be found in my original po开发者_如何学JAVAst.

Please help!


@brands is an Array, not a single ActiveRecord object, so you can't call the subbrands association directly on it. Since you're calling Brand.all, and I assume all Subbrand items are associated with a Brand, you might as well just query all of the Subbrand objects separately:

@brands = Brand.all
@subbrands = Subbrand.all

However, if you were trying to only get a subset of the brands, you could do this. (The second line queries all the subbrands that have a brand_id included in @brands).

@brands = Brand.where(...)
@subbrands = Subbrand.where(:brand_id => @brands.collect(&:id))
0

精彩评论

暂无评论...
验证码 换一张
取 消