当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - Filter has_many by attribute value

问题描述:

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.

网友答案:

Where is your controller action getting the product title (params[:title]) from? If you're just passing it in as a search term submitted through a form, then you should be able to run something like....

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

EDIT: Storing the associated products in the @company variable would be problematic because then @company will contain an array of associated products (instead of a Company object), which not only limits the information you can access about the specific company in your show action from that variable, it also becomes confusing (e.g you're using a variable named @company to store a list of products associated to a company)

分享给朋友:
您可能感兴趣的文章:
随机阅读: