Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # == Schema Information
- #
- # Table name: products
- #
- # id :integer not null, primary key
- # name :string
- # price :decimal(12, 2)
- # created_at :datetime not null
- # updated_at :datetime not null
- #
- class Product < ApplicationRecord
- has_many :categories
- after_create :save_categories
- #attr_reader :categories
- validates :name, presence: true
- validates :price, presence: true
- #Custom setter
- def categories=(value)
- @categories = value
- end
- private
- def save_categories
- @categories.each do |category_id|
- HasCategory.create(category_id: category_id, product_id: self.id) #self es una instancia de product
- end
- end
- end
- # == Schema Information
- #
- # Table name: has_categories
- #
- # id :integer not null, primary key
- # product_id :integer
- # category_id :integer
- # created_at :datetime not null
- # updated_at :datetime not null
- #
- class HasCategory < ApplicationRecord
- belongs_to :product
- belongs_to :category
- end
- # == Schema Information
- #
- # Table name: categories
- #
- # id :integer not null, primary key
- # name :string
- # created_at :datetime not null
- # updated_at :datetime not null
- #
- class Category < ApplicationRecord
- validates :name, presence: true
- has_many :products
- end
- <div class="container">
- <div class="row">
- <div class="col-sm-4 col-sm-offset-4">
- <h1><%= form_title %></h1>
- <% if @product.errors.any? %>
- <div class="alert alert-danger">
- <ul>
- <% @product.errors.full_messages.each do |msg| %>
- <li><%= msg %></li>
- <% end %>
- </ul>
- </div>
- <% end %>
- <%= form_for @product do |f| %>
- <div class="form-group">
- <%= f.text_field :name, class: "form-control input-lg", placeholder: "Nombre del producto"%>
- </div>
- <div class="form-group">
- <%= f.number_field :price, class: "form-control input-lg", placeholder: "Precio del producto" %>
- </div>
- <div class="field">
- <% if !@categories.nil? %>
- <% @categories.each do |category| %>
- <div class="field">
- <%= check_box_tag "categories[]", category.id %> <%= category.name %>
- </div>
- <% end %>
- <% end %>
- </div>
- <div>
- <%= f.submit form_title, class: "btn btn-primary btn-lg btn-block" %>
- </div>
- <% end %>
- </div>
- </div>
- </div>
Add Comment
Please, Sign In to add comment