【发布时间】:2015-05-14 12:30:15
【问题描述】:
我有模型“Post”。以及创建新记录的表格。
<%= 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 %>
而且我有不同的 Post 投票,我想将默认值设置为 1。我该怎么做?
我使用 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
【问题讨论】:
-
在数据库上设置默认值。
-
不要编辑现有的迁移文件,这是一种不好的做法。您将不得不回滚,然后编辑,然后再次运行迁移。最好写一个新的迁移并在那里做。
标签: ruby-on-rails ruby