Performance: Action methods
Action methods impact server response time and how quickly the browser receives HTML to start rendering.
def show @user = User.find(params[:id]) @posts = Post.where(user_id: @user.id).limit(10) render :show end
def show @user = User.find(params[:id]) @posts = Post.all sleep(2) # simulate slow operation render :show end
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy action with blocking calls | N/A (server-side) | N/A | Delays initial paint | [X] Bad |
| Optimized action with minimal queries | N/A (server-side) | N/A | Faster initial paint | [OK] Good |
action method in a Rails controller?show in a Rails controller?def method_name; end.def index @users = User.all end
@users contain after this action runs?User.all in RailsUser.all fetches all records from the users table as an ActiveRecord collection (like an array).@usersdef create
@user = User.new(params[:user])
if @user.save
redirect_to @user
else
render :new
end
endparams[:user] directly is unsafe and will cause an error in modern Rails.publish to your PostsController that changes a post's status to 'published' and then redirects to the post's page. Which code snippet correctly implements this?Post.find(params[:id]).save, then redirects. def publish
@post = Post.find(params[:id])
@post.save(status: 'published')
redirect_to @post
end incorrectly uses save(status: 'published') which is invalid.post_path(@post) which is also correct.Pass the test and this pattern moves unknown