Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing additional parameters to Rails Generate Model?

I'm new to Ruby and Rails and I'm running Rails 3 on Ruby 1.9.2.

I want to create a model, so I looked at the documentation to get the table definition that I want, but I wonder how I would pass this to rails generate model?

Basically I want this:

title :string, :null => false
details :text, :limit => 30000, :null => false

But I can only specify the column name and type, not :null or :limit.

I've tried rails model generate Article (title:string, :null => false) (details:text, :limit=>30000, :null => false) but that just tells me that ( is an unexpected token.

If I just generate the model with title:string details:text then the article.rb file is empty, presumably because it's read from the DB anyway.

As everything in Rails is supposed to be a) simple and b) magic, I'm wondering if I'm just missing something and have to pass something like a hash to generate model? Or do I really have to manually edit the migration .rb file?

like image 540
Michael Stum Avatar asked Dec 30 '10 12:12

Michael Stum


4 Answers

As it turns out, the limit can (now) be specified in the command line:

rails generate model user pseudo:string{30}

Source: usage doc from Rails GitHub project

Setting the default, however, still appears to require editing the migration manually.

For additional migration options, see the official Rails migrations guide.

like image 129
DreadPirateShawn Avatar answered Oct 05 '22 21:10

DreadPirateShawn


Yes you do have to manually edit the migration file for that. The generator just offers a starting point, it does not do everything.

Doing this in the migration file is very easy anyway.

create_table :articles do |t|
  t.string :title, :null => false
  t.text   :details, :limit => 3000, :null => false
end
like image 44
edgerunner Avatar answered Oct 05 '22 20:10

edgerunner


Try some tricks: belongs_to and index

rails g model User username:string:index group:belongs_to

This will create:

class User < ActiveRecord::Base
  belongs_to :group
  attr_accessible :username
end
like image 27
kuboon Avatar answered Oct 05 '22 21:10

kuboon


You can pass "null".to_sym => false in your rails generate model.
For example:

rails g model client 'ClientName, "null".to_sym => false:string{100}'

This will turn the "null" into a symbol, allowing it to run properly when running db:migrate

like image 30
Jimmy Salame Avatar answered Oct 05 '22 21:10

Jimmy Salame