0

I have model "Post". And the form for creating new record.

<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
  <div id="error_explanation">
  <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

  <ul>
  <% @post.errors.full_messages.each do |message| %>
    <li><%= message %></li>
  <% end %>
  </ul>
</div>
<% end %>

<div class="field">
  <%= f.label :title %><br>
  <%= f.text_field :title %>
</div>

<div class="actions">
  <%= f.submit %>
</div>
<% end %>

And I have variabe vote of Post which I want set default value 1. How can I do it?

My migration with change_column_default

class CreatePosts < ActiveRecord::Migration

  change_column_default :posts, :suit, false

  change_column_default :posts, :vote, 1

  def change
    create_table :posts do |t|
    t.string :title
    t.string :url
    t.string :tags
    t.boolean :suit
    t.integer :vote

    t.timestamps null: false
  end
 end
end
tencet
  • 382
  • 5
  • 18
  • Set a default on the database. – j-dexx Mar 12 '15 at 11:18
  • try reading http://stackoverflow.com/questions/1550688/how-do-i-create-a-default-value-for-attributes-in-rails-activerecords-model – Ian Kenney Mar 12 '15 at 11:19
  • 1
    Do not edit existing migration file, it's a bad practice. You will have to rollback, then edit, then run migration again. Better write a new migration and do it there. – Sharvy Ahmed Mar 12 '15 at 11:40

2 Answers2

1

If 'vote' is a database attribute and you want it to be '1' by default you should use a migration to set the default value in your database schema:

class SetPostVoteDefault < ActiveRecord::Migration

  change_column_default :posts, :vote, 1

end
Florian Eck
  • 495
  • 3
  • 13
  • Do not edit existing migration file, it will create problems for others if you are working for a big project. Instead generate a new migration and edit that migration file according to your need. – Sharvy Ahmed Mar 12 '15 at 11:37
0

If you want to do it explicitly through a new migration, In terminal :

rails g migration change_vote_default_in_posts

In migration file :

class ChangeVoteDefaultInPosts < ActiveRecord::Migration

    def up
      change_column_default :posts, :vote, 1
    end

    def down
      change_column_default :posts, :vote, nil
    end
end

In terminal:

rake db:migrate
Sharvy Ahmed
  • 7,247
  • 1
  • 33
  • 46