random_user_0891
random_user_0891

Reputation: 2051

default value in column not submitting with form

I added a default value for a column in a migration file but it will not submit with the form it just shows as an empty string in the database. I can use the dropdown to select additional categories and those will save, however the default value of "all users" will not.

I'm on Rails 4.2.4

migration file

class AddPrivacyLevelToArticles < ActiveRecord::Migration
  def change
    add_column :articles, :privacy_level, :string, default: "All Users"
  end
end

field in my form.

  <div class="form-group private_categories">
    <%= f.label :privacy_level, { :class => "col-sm-2 control-label" } %>
    <div class="col-sm-4">
      <%= f.select :privacy_level, Article::PRIVACY_CATEGORIES,
        { include_blank: 'Please Select' }, class: "form-control" %>
    </div>
  </div>

in Article model

  PRIVACY_CATEGORIES = ["Me only", "My Organization", "Multiple Organizations"]

Upvotes: 0

Views: 54

Answers (1)

7urkm3n
7urkm3n

Reputation: 6311

You can use enum for it. Doc

# models/article.rb
enum privacy_level: { all_users: 0, me_only: 1, 
                      my_organization: 2, 
                      multiple_organizations: 3}

#or
enum privacy_level:  [:all_users, :me_only, 
                      :my_organization, 
                      :multiple_organizations]


#migration
add_column :articles, :privacy_level, :integer, default: 0


# View - form
Article.privacy_levels
=> {"all_users" => 0, "me_only" => 1 ...}

Upvotes: 1

Related Questions