开发者

Rails Model Property Location

开发者 https://www.devze.com 2023-02-10 17:31 出处:网络
I\'m working through the Ruby on Rails tutorial and just made a Comment model with three properties. rails generate model Comment commenter:string body:text post:references

I'm working through the Ruby on Rails tutorial and just made a Comment model with three properties.

rails generate model Comment commenter:string body:text post:references

It generated an ActiveRecord class with post but not commenter and body.

class Comment < ActiveRecord::Base
  belongs_to :post
end

Why doesn't rails formally define the non-reference properties anywhere开发者_如何学编程 other than the DB migration scripts?


Rails dynamically loads attributes - specifically, the names of the columns and their types - based on the database schema. There is no need to define or declare them in your models. For apps running in production, it does this once, at load time. For development, it will reload them as often as every request, but only loads them when each model is used.

Rails does not infer other things from your database, though. For instance, if you were to place a unique index on a name column, it would not automatically add a validates_uniqueness_of :name to your model. Of course, the database would still enforce this constraint when you save the record, causing an exception to be raised should the name field contain a duplicate value. The recommendation, in this case, is to do both.


Why doesn't rails formally define the non-reference properties anywhere other than the DB migration scripts?

Well, where do you need them "defined" anyways? Migrations are the only place where these attributes matter coz its responsibility is to create database tables with those attributes.

If you do a scaffold on comments with similar parameters, it would also generate the views and it would be using the attributes. They don't need to be "defined" as such anywhere else.


The short answer to your question is "no". Even the migration is not a definitive place to look as there might be many migrations related to a model.

However, you may have a look at the generated "db/schema.rb" which is an aggregation of all migrations. It contains the schema definition of all activerecord models. This maybe your best bet.

Additionally, you may want to use the https://github.com/ctran/annotate_models plugin that inserts a comment in your model to help you keep track of all your model's attributes.

0

精彩评论

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