在一次迁移中添加多个列

时间:2011-02-14 21:54:58

标签: ruby-on-rails-3 migration

场景:我们已经有了 Document 模型,我们想添加

  • 公共
  • 私有

或更多列使用单个迁移。

到目前为止,我从搜索和阅读的内容中,您只需编辑迁移文件即可。如果已应用迁移,则回滚并再次迁移。

  1. 这是常见的最佳做法,还是有更好的方法?
  2. 如果这样做的话,该迁移的正确命名是什么?

3 个答案:

答案 0 :(得分:61)

如果迁移是本地迁移并且尚未推送到任何存储库,则回滚迁移并重新编辑它是唯一安全的。编辑其他人已应用的迁移可能会导致问题。

将列添加到现有表的最安全方法是创建新的迁移:

rails g migration add_public_and_private_to_document public:string private:string

如果使用add_[column_names]_to_[model]命名约定,rails将找出相应的表并创建所需的迁移。

请阅读此处以获取更多信息:http://guides.rubyonrails.org/migrations.html

答案 1 :(得分:2)

@Cam方式很严格。除了在运行迁移后你需要更新两件事。

所以,让我们说我有一个名为myapp的现有脚手架,我想为该脚手架添加更多字段。要做的三件事。

要添加的字段是:

=>

1)rails g migration add_term_count_and_current_record_count_and_previous_record_count_to_myapp term_count:integer , current_record_count:integer , previous_record_count:integer

=>

2) Update views, example updating _form.html.rb

我需要添加:

<div class="field">
    <%= f.label :current_record_count %><br>
    <%= f.number_field :current_record_count%>
  </div>

 <div class="field">
    <%= f.label :current_record_count %><br>
    <%= f.number_field :previouse_record_count%>
  </div>

  <div class="field">
    <%= f.label :term_count  %><br>
    <%= f.number_field :terminations_count %>
  </div>

=&GT;

3) Update Controller : 

新版本的rails具有所谓的强参数,可防止黑客传递任意列字段值。简而言之,使用新字段名称更新方法,否则您将看不到新字段。

 # Never trust parameters from the scary internet, only allow the white list through.

def vendor_file_params
    params.require(:vendor_file).permit(:name, :run_date,  :term_count ,
    :current_record_count , :previous_record_count ,:comments)   
end
end

答案 2 :(得分:0)

您可以发出如下命令:

rails g migration document public:string private:string

相关问题