简体   繁体   中英

Calling associated models in rails

My association is

restaurant.rb (model)

has_many :products

and in products.rb (model)

belongs_to :restaurant

Now in my products controller i am basically trying to generate a list of all products and search them with some validation. I want to show only those products which belong to a specific restaurant

def index
                
                case params[:status]
                when 'Active'
                    active_products
                when 'Inactive'
                    inactive_products    
                when 'Sold out'
                    sold_out
                else
                    @products = Restaurant.Product.all #problem arises here
                end

                if params[:search]
                    search
                end

                if params[:section]
                    section
                end

                if params[:sort_by]
                    product_sort
                end
                
            end

In the 'else' block of case i want products according to restaurant id. How can i do that?

Product.where(restaurant_id: some_id).all

You could also do something like

Restaurant.find(restaurant_id).products

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM