1

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?

Backo
  • 18,291
  • 27
  • 103
  • 170
  • 2
    @Awea How is this possibly a duplicate of that question? referenced question asks about validation not working, this one talks about query being fired every time when validation runs. – rubish Aug 25 '11 at 13:25

1 Answers1

1

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.

rubish
  • 10,887
  • 3
  • 43
  • 57
  • Thanks, so in production mode the SQL query doesn't happen... good! But, if I do not call the 'map' method the query will be lazy loaded or not? – Backo Aug 25 '11 at 13:10
  • In that case it should be lazy loaded, but you do not want the lazy loading in this case. – rubish Aug 25 '11 at 13:22