简体   繁体   中英

How does Ruby on Rails work with an “inclusion” validation?

I am using Ruby on Rails v3.0.9 and I have the following code in a my model:

class User < ActiveRecord::Base
  validates :users_role,
    :inclusion => {
      :in      => UserRole.all.map(&:role)
    },
    :presence  => true
end

When I browse an UserRole related page (that is, a page where an user object instance is involved - for example, the RoR conventional "show" or "index" views), and I inspect the log file I see that the UserRole SQL query is performed. That is, the UserRole.all.map(&:role) run.

I would like to know how Ruby on Rails works for the above case. It concerns the performance? Is the UserRole.all.map(&:role) lazy loaded?

In your dev environment you will probably see that query running on any request which validates user, as code is reloaded on each request. Try it in production mode once, it should not happen in that case, as code is loaded once only and you haven't put the query in a lambda. There should be no lazy loading here as you already called map on the resultset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM