Atchyut Nagabhairava
Atchyut Nagabhairava

Reputation: 1433

How to set some default values in a column in rails

I'm developing an 'expense manager' app which helps the users to manage their expenses and generate reports with Graphs and also they can get the expenses sorted by date or by period of time.

A user can login add expenses and select a category for each expense from a dropdown.

Upto here everything went well, But I was stuck with a doubt if there is any possibility to add some default categories in the categories table when the user sign up. I also have a requirement for the user to delete these default categories which should not effect other users categories.

Please suggest me an idea how we can deal with this requirement instead of using Seed data.

Migration for creating categories

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end

Category drop down in expense new form

    <div class="form-group">
      <%= f.label :category, "Category:" %><br>
    <div class="col-md-2">    
       <%= f.collection_select(:category_id, current_user.categories, :id, :name, {}, { :class => "select_box selectpicker picker"}) %>
    </div>
  </div>

Git repository of this app: https://github.com/atchyut-re/expense_manager

Hope I'm clear if I need to give any further details please mention in comment.

Upvotes: 0

Views: 505

Answers (2)

Emu
Emu

Reputation: 5905

Create a after_create callback in your user model to create some categories. As the categories are user dependent, then there should be an association between user & categories.

Upvotes: 2

Hieu Pham
Hieu Pham

Reputation: 6692

You can simply use rails call back to create the default categories for every user, the code will be like:

class User < ActiveRecord::Base
  before_create :create_default_categories

  DEFAULT_CATEGORIES = [
     {name: 'default name 1', other_attribute: 'default other attribute 1'},
     {name: 'default name 2', other_attribute: 'default other attribute 2'}
  ]

  def create_default_categories
    DEFAULT_CATEGORIES.each do |default_attrs|
      self.categories.build(default_attrs)
    end
  end
end

So when user was created, the default categories would be created as well!

Upvotes: 1

Related Questions