Reputation: 2763
Hello Guys I have a question,
for example I have a model Product
who has
:title, :description, :category_id
. And the product belongs_to :category
and I have a model Category
who has :name
. And has_many :products
I'm trying to do a scope who will use the method where. I try for example Product.where(category_id: 2)
and I have all the products who was saved with the id=2.
But my question is if I want to put in the clause where using the category.name: 'some_category'
. How can I do?
Upvotes: 0
Views: 77
Reputation: 2763
I find a best answer for what I want to do and know I want to share here, first I install a gem has_scope
.
Then in my Product model I do this scope:
scope :category, -> category_id {where(:category_id => category_id)}
Then in the products_controller I put:
has_scope :category
and
def index
@products = apply_scopes(Product).all
end
And then in my navbar I put this links:
<li><%= link_to 'Oils', category: 1 %></li>
<li><%= link_to 'Wines', category: 2 %></li>
and this was posible for show just these types of products by category. But there has a problem with this! It will work just if you click firstly in the Products.path where will show all the products and then if you click on these links will works fine. But when I click in other link like Contact.path and then click on Oils link it will show in the navigator /contact?category=1 and then will not show the products filtered like I want.
Then the solution for fix this problem was:
<li><%= link_to 'Azeites', '/products?category=1' %></li>
<li><%= link_to 'Vinhos', '/products?category=2' %></li>
And every time you click will show perfectly, very simple and practice. Thank's guys for help me!
Upvotes: 0
Reputation: 76774
#app/models/product.rb
class Product < ActiveRecord::Base
scope :by_category, ->(name) { joins(:category).where(categories: {name: name}) }
end
This will allow you to call:
@cars = Product.by_category("cars")
Upvotes: 0
Reputation: 3899
Product.joins(:category).where(categories: { name: string_or_array_of_names })
using string_or_array_of_names
as your variable
Upvotes: 2
Reputation: 18127
You can use joins
and references
.
Product.joins(:category).references(:category).where("categories.name = ?", "a name")
Upvotes: 0