【问题标题】:Different types of Model fields in ruby on rails?ruby on rails中不同类型的模型字段?
【发布时间】:2020-05-14 08:56:52
【问题描述】:

我在 Rails 中创建了一个模型,我需要一些与模型的每个实例相关的日期和时间属性。我无法找到 rails 提供的所有类型的字段,如字符串、布尔值、文本等?谁能给我一个链接,这将是一个很大的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby rubygems ruby-on-rails-5


    【解决方案1】:

    要查看有关模型的可用帮助,您可以运行命令rails g model。 命令和模型有很多细节。以下是关于字段类型的摘录,希望对您有所帮助。

    可用的字段类型:

    Just after the field name you can specify a type like text or boolean.
    It will generate the column with the associated SQL type. For instance:
    
        `rails generate model post title:string body:text`
    
    will generate a title column with a varchar type and a body column with a text
    type. If no type is specified the string type will be used by default.
    You can use the following types:
    
        integer
        primary_key
        decimal
        float
        boolean
        binary
        string
        text
        date
        time
        datetime
    
    You can also consider `references` as a kind of type. For instance, if you run:
    
        `rails generate model photo title:string album:references`
    
    It will generate an `album_id` column. You should generate these kinds of fields when
    you will use a `belongs_to` association, for instance. `references` also supports
    polymorphism, you can enable polymorphism like this:
    
        `rails generate model product supplier:references{polymorphic}`
    
    For integer, string, text and binary fields, an integer in curly braces will
    be set as the limit:
    
        `rails generate model user pseudo:string{30}`
    
    For decimal, two integers separated by a comma in curly braces will be used
    for precision and scale:
    
        `rails generate model product 'price:decimal{10,2}'`
    

    【讨论】:

    • 感谢您的帮助,我只有一个问题,我正在设计一个用户可以选择服务的应用程序,我有服务名称和价格的服务模型,我应该如何将用户与这种服务模型,以便用户可以选择数据库中存在的 1 个、2 个或多个服务?
    • 基本上,你需要两种资源,一种用于用户,另一种用于服务资源。您需要知道其中哪些或全部? “用户可以使用的服务列表”,“分配服务的用户列表”。因此决定它是一对多还是多对多。请在此处阅读:edgeguides.rubyonrails.org/association_basics.html 以获取更多信息。
    猜你喜欢
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2013-08-02
    • 2015-05-03
    • 2011-04-26
    • 1970-01-01
    相关资源
    最近更新 更多