tencet
tencet

Reputation: 505

Set defauls values Rails

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

Upvotes: 0

Views: 55

Answers (2)

Sharvy Ahmed
Sharvy Ahmed

Reputation: 7405

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

Upvotes: 0

Florian Eck
Florian Eck

Reputation: 495

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

Upvotes: 1

Related Questions