开发者

varchar Migration question for Ruby on Rails

I have created a new table includi开发者_如何学编程ng a column "note". The default is varchar(255) I believe but I wish to have this column be a text area vs. a field and to allow more data. I imagine that I would make this change in ActiveRecord::Migration file but I am curious as to the format. Do I simply change the varchar(255) to varchar(1000) for example? (if so what is the format?

def self.up
    create_table :notes do |t|
      t.string :note :varchar(1000)
    end

Is that the right format? Furthermore, how do I get the entry field to be multiple rows. Sorry if this is easy stuff but I am new to programming and RoR. Thanks.


The correct format would be

t.string :note, :limit => 1000

make sure you are using a version of MySQL(or whichever database) which supports varchars longer than 256 characters.

if you want to use a large text block it would be

t.text :note

See http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html for more information


You can change the length with the limit option as so...

def self.up
  change_column :notes, :note, :string, :limit => 1000
end


You can simply use the 'text' type instead of 'string'.

def self.up
  create_table :notes do |t|
    t.text :note
  end
end

Using the 'text' type will result in database column of type TEXT. Varchar is usually limited to a maximum length of 255 (in MySQL, other RDBMSs have similar limits).

If you use Rails' form helpers, a textarea will be output for this field (because it is of type 'text'). textarea is the form element that accepts multi-line input.

Edit: If you've already migrated the create_table, you can create a new migration to change the column type:

def self.up
  change_column :notes, :note, :text
end


Since I had a lot of data already stored I used

self.up
  change_column :notes, :note, :text, :limit => nil
end

If I left off the :limit => nil option then the column type would change from varchar to text, but it still had a max length of 255 characters.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜