Guest User

Untitled

a guest
Nov 24th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. # == Schema Information
  2. #
  3. # Table name: products
  4. #
  5. # id :integer not null, primary key
  6. # name :string
  7. # price :decimal(12, 2)
  8. # created_at :datetime not null
  9. # updated_at :datetime not null
  10. #
  11.  
  12. class Product < ApplicationRecord
  13. has_many :categories
  14.  
  15. after_create :save_categories
  16.  
  17. #attr_reader :categories
  18.  
  19. validates :name, presence: true
  20. validates :price, presence: true
  21.  
  22. #Custom setter
  23. def categories=(value)
  24. @categories = value
  25. end
  26.  
  27. private
  28.  
  29. def save_categories
  30. @categories.each do |category_id|
  31. HasCategory.create(category_id: category_id, product_id: self.id) #self es una instancia de product
  32. end
  33. end
  34.  
  35. end
  36.  
  37. # == Schema Information
  38. #
  39. # Table name: has_categories
  40. #
  41. # id :integer not null, primary key
  42. # product_id :integer
  43. # category_id :integer
  44. # created_at :datetime not null
  45. # updated_at :datetime not null
  46. #
  47.  
  48. class HasCategory < ApplicationRecord
  49. belongs_to :product
  50. belongs_to :category
  51. end
  52.  
  53. # == Schema Information
  54. #
  55. # Table name: categories
  56. #
  57. # id :integer not null, primary key
  58. # name :string
  59. # created_at :datetime not null
  60. # updated_at :datetime not null
  61. #
  62.  
  63. class Category < ApplicationRecord
  64. validates :name, presence: true
  65. has_many :products
  66. end
  67.  
  68. <div class="container">
  69. <div class="row">
  70. <div class="col-sm-4 col-sm-offset-4">
  71. <h1><%= form_title %></h1>
  72.  
  73. <% if @product.errors.any? %>
  74. <div class="alert alert-danger">
  75. <ul>
  76. <% @product.errors.full_messages.each do |msg| %>
  77. <li><%= msg %></li>
  78. <% end %>
  79. </ul>
  80. </div>
  81. <% end %>
  82.  
  83. <%= form_for @product do |f| %>
  84. <div class="form-group">
  85. <%= f.text_field :name, class: "form-control input-lg", placeholder: "Nombre del producto"%>
  86. </div>
  87. <div class="form-group">
  88. <%= f.number_field :price, class: "form-control input-lg", placeholder: "Precio del producto" %>
  89. </div>
  90. <div class="field">
  91. <% if !@categories.nil? %>
  92. <% @categories.each do |category| %>
  93. <div class="field">
  94. <%= check_box_tag "categories[]", category.id %> <%= category.name %>
  95. </div>
  96. <% end %>
  97. <% end %>
  98. </div>
  99. <div>
  100. <%= f.submit form_title, class: "btn btn-primary btn-lg btn-block" %>
  101. </div>
  102. <% end %>
  103. </div>
  104. </div>
  105. </div>
Add Comment
Please, Sign In to add comment