I have a custom CRUD controller. When I open the user edit page in a browser, my log shows this:
Started GET "/users/1/edit" for 127.0.0.1 at 2011-06-21 20:09:37 +0200 Processing by UsersController#edit as HTML Parameters: {"id"=>"1"} User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = ? LIMIT 1 [["id", 1]] User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = ? LIMIT 1 [["id", "1"]]
In the edit action, I just call the user of the private function, which returns
@user ||= User.find(params[:id])
The view is as follows:
<%= settings_title(@user.username) %> <%= form_for @user, :html => { :multipart => true } do |f| %> <%= render "form", :user => @user <div class="action"><%= submit_tag t("users.edit.submit"), :class => "button" %></div> <%= end %>
A route is defined as resources :users do ...
Any idea how to prevent second access to db would be greatly appreciated!
Update:
It seems that the second DB SELECT can be prevented by calling
@user ||= User.find(params[:id].to_i)
in action editing. Now I get:
User Load (0.1ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = ? LIMIT 1 [["id", 1]] CACHE (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = ? LIMIT 1
but is this the right way to do this? Do you see any other side effects of this solution?
source share