Adding a column to a model at runtime (without additional tables) in rails

走远了吗. 提交于 2019-12-23 12:46:00

问题


I'm trying to give admins of my web application the ability to add some new fields to a model. The model is called Artwork and i would like to add, for instante, a test_column column at runtime. I'm just teting, so i added a simple link to do it, it will be of course parametric.

I managed to do it through migrations:

  def test_migration_create  
   Artwork.add_column :test_column, :integer
    flash[:notice] = "Added Column test_column to artworks"
    redirect_to :action => 'index'
  end

  def test_migration_delete
    Artwork.remove_column :test_column
    flash[:notice] = "Removed column test_column from artworks"
    redirect_to :action => 'index'
  end

It works, the column gets added/ removed to/from the databse without issues. I'm using active_scaffold at the moment, so i get the test_column field in the form without adding anything. When i submit a create or an update, however, the test_column does not get updated and stay empty. Inspecting the parameters, i can see:

Parameters: {"commit"=>"Update", "authenticity_token"=>"37Bo5pT2jeoXtyY1HgkEdIhglhz8iQL0i3XAx7vu9H4=", "id"=>"62", "record"=>{"number"=>"test_artwork", "author"=>"", "title"=>"Opera di Test", "test_column"=>"TEEST", "year"=>"", "description"=>""}}

the test_column parameter is passed correctly. So why active record keeps ignoring it? I tried to restart the server too without success.

I'm using ruby 1.8.7, rails 2.3.5, and mongrel with an sqlite3 database.

Thanks


回答1:


In the development environment, ActiveRecord models reload their metadata upon every request. In the production environment, however, metadata is cached at startup, so any columns you add will not be easily accessible until that metadata is refreshed.

Also, altering a table usually requires an exclusive table lock while the data is rewritten, which could really hurt your site's performance.



来源:https://stackoverflow.com/questions/2749760/adding-a-column-to-a-model-at-runtime-without-additional-tables-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!