Guest User

Untitled

a guest
Jan 17th, 2019
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. def index
  2. @products = product.all
  3.  
  4. if params[:country]
  5. @products = Country.find(params[:country]).products
  6. end
  7.  
  8. if params[:category]
  9. @products = Category.find(params[:category]).products
  10. end
  11.  
  12. end
  13.  
  14. class Product < ActiveRecord::Base
  15.  
  16. has_many :categorization
  17. belongs_to :country
  18.  
  19. end
  20.  
  21. class Category < ActiveRecord::Base
  22. has_many :categorization
  23. has_many :products, through: :categorization
  24.  
  25. attr_accessible :name
  26.  
  27. end
  28.  
  29. class Categorization < ActiveRecord::Base
  30. belongs_to :category
  31. belongs_to :product
  32.  
  33. attr_accessible :category, :product
  34. end
  35.  
  36. <div class="wrapper">
  37. <div class="products">
  38. </div>
  39. <div class="sidebar>
  40. <h2>Categories</h2>
  41. <ul>
  42. <% @categories.each do |category| %>
  43. <li><%= link_to category.name, params.merge(category: category.id) %></li>
  44. <% end %>
  45. </ul>
  46. <h2>Countries</h2>
  47. <ul>
  48. <% @countries.each do |country| %>
  49. <li><%= link_to country.name, params.merge(country: country.id) %></li>
  50. <% end %>
  51. </ul>
  52. </div>
  53. </div>
  54.  
  55. # Product Model
  56.  
  57. class Product < ActiveRecord::Base
  58.  
  59. # Search filter
  60. def self.filter_by_params(params)
  61. if params.has_key?(:category) && params.has_key?(:country_id)
  62. scoped.joins(:categorization).where("category_id = ? AND country_id = ?", params[:category], params[:country_id])
  63. elsif params.has_key?(:category)
  64. scoped.joins(:categorization).where("category_id = ?", params[:category])
  65. elsif params.has_key?(:country_id)
  66. scoped.where(country_id: params[:country_id])
  67. else
  68. scoped
  69. end
  70. end
  71.  
  72. end
  73.  
  74. # Product Controller
  75.  
  76. def index
  77. @product = Product.filter_by_params(params)
  78. end
  79.  
  80. def index
  81. @products = Product.filter_by_params(params)
  82. end
  83.  
  84. def self.filter_by_params(params)
  85. scoped = self.scoped.where(:country_id => params[:country_id]) if params[:country_id]
  86. scoped = scoped.where(:category_id => params[:category_id]) if params[:category_id]
  87. scoped
  88. end
Add Comment
Please, Sign In to add comment