views:

17

answers:

0

Just getting through some of the issue backlog and could use some input on best-practices for what seems like it should be a common scenario. (Rails 2.3.5)

Let's say we've got form for creating posts for a blog using mass-assignment. The create action looks something like:

def create
  if @blog.update_attributes(params[:blog])
    redirect_to :action => :index
  else
    # @new_posts is used in the form's fields_for call to show only new items.
    # This is the bit that seems very inefficient, is there a better way?
    @new_posts = @blog.posts.select(&:new_record?)
    render :action => :new
  end
end

Is there a way to efficiently access just the new_record?s of @blog after the validation failure without iterating over all of the existing posts? This seems like a pretty common scenario, and the above code would be frighteningly inefficient when there are a large number of posts for a blog. Ideas?