【问题标题】:Set defauls values Rails设置默认值 Rails
【发布时间】: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


【解决方案1】:

如果 'vote' 是一个数据库属性,并且您希望它默认为 '1',您应该使用迁移来设置数据库架构中的默认值:

class SetPostVoteDefault < ActiveRecord::Migration

  change_column_default :posts, :vote, 1

end

【讨论】:

  • 不要编辑现有的迁移文件,如果你正在为一个大项目工作,它会给其他人带来问题。而是生成一个新的迁移并根据您的需要编辑该迁移文件。
【解决方案2】:

如果您想通过新的迁移明确地做到这一点, 在终端:

rails g migration change_vote_default_in_posts

在迁移文件中:

class ChangeVoteDefaultInPosts < ActiveRecord::Migration

    def up
      change_column_default :posts, :vote, 1
    end

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

在终端:

rake db:migrate

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 2010-09-24
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多