0

I'm trying to find the best solution to filter the objects in a has_many association. What I have for a setup is

class Company < ActiveRecord::Base
  has_many :products
end

class Product < ActiveRecord::Base
  attr_accessible :title
  belongs_to :company
end

Then in my CompaniesController#show method what I'd like to do is filter the products by it's title.

def show
  @company = Company.find(params[:id])
  # Then I just want the @company.products where title = params[:title]
end

Any help would be greatly appreciated.

4

1 回答 1

0

您的控制器操作从哪里获取产品标题 (params[:title])?如果您只是将其作为通过表单提交的搜索词传递,那么您应该能够运行类似...。

 @products = @company.products.where("title = ?", params[:title])

编辑:将关联产品存储在@company 变量中会出现问题,因为@company 将包含关联产品数组(而不是 Company 对象),这不仅限制了您在展示操作中可以访问的有关特定公司的信息从该变量中,它也会变得混乱(例如,您正在使用名为 @company 的变量来存储与公司关联的产品列表)

于 2013-03-22T18:45:11.570 回答