Create new category with ruby on rails

RUBY ON RAIL

Posted on 2016-11-30 22:36:24


 In model, you need add check validate for category

validates :name,  presence: true

You need read article before work with create new category

Management categories in ruby on rails

Edit category in ruby on rails

1. In controller

def new

    @category = Category.new

    @parent_categories = Category.where(:parent_category_id => nil).all

  end

 

  def create

    @parent_categories = Category.where(:parent_category_id => nil).all

    @category = Category.new(category_params)

    if @category.save

      flash[:success] = "Create success"

      redirect_to categories_url

    else

      render 'new'

    end

  end

 

@parent_categories = Category.where(:parent_category_id => nil).all

This query get all parent categories with id is null

If status for saving data is success, system will showed massage " Create success " else keep on new function

2. In view file

I used haml file replace main view file ruby on rails .html.erb

new.haml

= provide(:title, 'New category')

%h1

  New category

 

.row

  .col-md-6.col-md-offset-3

    = form_for(@category) do |f|

      = render 'error_messages'

 

      = f.label :parent_category_id

      = f.select :parent_category_id, options_for_select(@parent_categories.collect{ |c| [c.name, c.id] }), {include_blank: "--- Select parent category ---"}, class: 'form-control'

 

      = f.label :name

      = f.text_field :name, class: 'form-control'

 

      = f.submit "Create category", class: "btn btn-primary"

3. render _error_messages.haml

- if @category.errors.any?

  #error_explanation

    .alert.alert-danger

      The form contains

      = pluralize(@category.errors.count, "error")

    %ul

    - @category.errors.full_messages.each do |msg|

 

      %li=msg


This is result