Create function edit category with selected parent category in selection

RUBY ON RAIL

Posted on 2016-11-30 22:29:07


Continue from function index category for show parent categories and sub categories

You should read http://tutscode.com/22578-Management-categories-with-show-parent-category-and-sub-category-in-rails.html before implement function create category


I make tutorial for edit category for guys

1. Create funciton edit category

def edit

    @category = Category.find(params[:id])

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

  end

@category = Category.find(params[:id])

This query get category edited by param id

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

This query get all parent categories with id is null

2. Create function update for edit category

def update

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

    @category = Category.find(params[:id])

    if @category.update_attributes(category_params)

      flash[:success] = "Category updated"

      redirect_to categories_url

    else

      render 'edit'

    end

  end

 

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

This is used for error validate name category

If status for saving data is success, system will showed massage "Category updated" else keep on edit function

3. edit view file with haml

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

edit.haml

= provide(:title, 'Edit category')

%h1

  Edit 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] }, @category.parent_category_id), {include_blank: "--- Select parent category ---"}, class: 'form-control'

 

      = f.label :name

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

 

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

 

4. 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 result