Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def index
- @products = product.all
- if params[:country]
- @products = Country.find(params[:country]).products
- end
- if params[:category]
- @products = Category.find(params[:category]).products
- end
- end
- class Product < ActiveRecord::Base
- has_many :categorization
- belongs_to :country
- end
- class Category < ActiveRecord::Base
- has_many :categorization
- has_many :products, through: :categorization
- attr_accessible :name
- end
- class Categorization < ActiveRecord::Base
- belongs_to :category
- belongs_to :product
- attr_accessible :category, :product
- end
- <div class="wrapper">
- <div class="products">
- </div>
- <div class="sidebar>
- <h2>Categories</h2>
- <ul>
- <% @categories.each do |category| %>
- <li><%= link_to category.name, params.merge(category: category.id) %></li>
- <% end %>
- </ul>
- <h2>Countries</h2>
- <ul>
- <% @countries.each do |country| %>
- <li><%= link_to country.name, params.merge(country: country.id) %></li>
- <% end %>
- </ul>
- </div>
- </div>
- # Product Model
- class Product < ActiveRecord::Base
- # Search filter
- def self.filter_by_params(params)
- if params.has_key?(:category) && params.has_key?(:country_id)
- scoped.joins(:categorization).where("category_id = ? AND country_id = ?", params[:category], params[:country_id])
- elsif params.has_key?(:category)
- scoped.joins(:categorization).where("category_id = ?", params[:category])
- elsif params.has_key?(:country_id)
- scoped.where(country_id: params[:country_id])
- else
- scoped
- end
- end
- end
- # Product Controller
- def index
- @product = Product.filter_by_params(params)
- end
- def index
- @products = Product.filter_by_params(params)
- end
- def self.filter_by_params(params)
- scoped = self.scoped.where(:country_id => params[:country_id]) if params[:country_id]
- scoped = scoped.where(:category_id => params[:category_id]) if params[:category_id]
- scoped
- end
Add Comment
Please, Sign In to add comment