首页 文章

Ruby on Rails生成模型字段:type - 字段的选项有哪些:type?

提问于
浏览
295

我正在尝试生成一个新模型并忘记引用另一个模型ID的语法 . 我自己查一下,但在我所有的Ruby on Rails文档链接中,我还没有弄清楚如何找到权威的来源 .

$ rails g model Item name:string description:text (此处为 reference:productreferences:product ) . 但更好的问题是,未来我可以在哪里或如何轻松地寻找这种愚蠢?

注意:我已经学到了很难的方法,如果我错误地输入其中一个选项并运行我的迁移,那么Ruby on Rails将完全搞砸我的数据库...并且 rake db:rollback 对这种搞砸是无能为力的 . 我只是不理解某些东西,但直到我做... rails g model 返回的"detailed"信息仍然让我感到搔痒......

6 回答

  • 7
    :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp,
    :time, :date, :binary, :boolean, :references
    

    请参阅table definitions部分 .

  • 3

    要创建引用另一个的模型,请使用Ruby on Rails模型生成器:

    $ rails g model wheel car:references
    

    那会产生 app/models/wheel.rb

    class Wheel < ActiveRecord::Base
      belongs_to :car
    end
    

    并添加以下迁移:

    class CreateWheels < ActiveRecord::Migration
      def self.up
        create_table :wheels do |t|
          t.references :car
    
          t.timestamps
        end
      end
    
      def self.down
        drop_table :wheels
      end
    end
    

    当您运行迁移时,以下内容将最终出现在 db/schema.rb 中:

    $ rake db:migrate
    
    create_table "wheels", :force => true do |t|
      t.integer  "car_id"
      t.datetime "created_at"
      t.datetime "updated_at"
    end
    

    至于文档,rails生成器的起点是Ruby on Rails: A Guide to The Rails Command Line,它指向API Documentation以获取有关可用字段类型的更多信息 .

  • 183

    $ rails g model Item name:string description:text product:references

    我也发现指南难以使用 . 容易理解,但很难找到我要找的东西 .

    另外,我有临时项目,我运行 rails generate 命令 . 然后,一旦我让他们工作,我在我的真实项目上运行它 .

    上述代码的参考:http://guides.rubyonrails.org/getting_started.html#associating-models

  • 3

    记住在编写此命令时不要将文本大写 . 例如:

    写道:

    rails g model product title:string description:text image_url:string price:decimal
    

    Do not write:

    rails g Model product title:string description:text image_url:string price:decimal
    

    至少这对我来说是一个问题 .

  • 0

    如果你想要了解Ruby on Rails中的基本内容,http://guides.rubyonrails.org应该是一个很好的网站 .

    以下是生成它们时关联模型的链接:http://guides.rubyonrails.org/getting_started.html#associating-models

  • 455

    我有同样的问题,但我的代码有点不同 .

    def new @project = Project.new end

    我的表格看起来像这样:

    <%= form_for @project do |f| %> and so on.... <% end %>

    那是完全正确的,所以我不知道如何解决这个问题 .

    最后,在 <%= form-for @project 之后添加 url: { projects: :create } 为我工作 .

相关问题