开发者

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

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 t开发者_如何学运维est_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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜