I'm creating a marketplace app where sellers can list items to sell. I want to create a category dropdown so customers can select a category to shop.
In my listing model, I have a 'category' field. When a user selects a category, I want the view to filter listings from that category.
In my routes.rb:
get '/listings/c/:category' => 'listings#category', as: 'category'
To create the category menu - in my index.html.erb:
<%= Listing.uniq.pluck(:category).each do |category| %>
<%= link_to category, category_path(category: category) %>
<% end %>
In my listings controller:
def category
@category = category
@listings = Listing.not_expired.where(:category => @category)
end
category.html.erb:
<% @listings.each do |listing| %>
#some html
<% end %>
The homepage category menu shows up. The routes are created. But when I click on the category, the url such as listings/c/necklaces gives me the stack level too deep error.
FYI "Stack Level Too Deep" basically means you have an infinite loop in your code somewhere
--
From what I can see, the error will be here:
def category
@category = category
With this code, you're basically invoking the category
method again, which in turn will invoke the category
method etc, in a never-ending cycle. This will prevent your application from being able to run without reloading itself in infinite recursion.
You should change it to:
def category
@category = params[:category]
@listings = Listing.not_expired.where(:category => @category)
end
However, a much more refined way would be:
#app/models/category.rb
class Category < ActiveRecord::Base
has_many :listings do
def not_available
#your not available method here
end
end
end
#app/models/listing.rb
class Listing < ActiveRecord::Base
belongs_to :category
end
#app/controllers/your_controller.rb
def category
@category = Category.find params[:categpry]
@listings = @category.listings.not_available
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.