Best Practices for Multiple Model Creation

15 views
Skip to first unread message

Matthew Johnston

unread,
Sep 24, 2012, 1:30:52 AM9/24/12
to rubyonra...@googlegroups.com
So I have a few models that need to be created, but only based on a few inputs. There is no need for nested attributes, in fact I would rather avoid this.

The way I have been doing it is like so


class WidgetsController < ApplicationController
  def create
    respond_to do |format|
      if current_user.create_widget(params[:foo])
        flash[:success] = "Processed your request"
      else
        flash[:error] = "There was a problem processing your request"
      end
      format.html { redirect_to widgets_path }
    end
  end
end

class User < ActiveRecord::Base

  def create_widget params
    User.transaction do
      widget = self.widgets.build.save!
      widget.blinky_lights.build(params[:foo]).save!
      true
    end
  end

end

In this contrived example, Widget is basically an entity that other crap will hang from. Is this even a decent build pattern or does someone have a better idea of how to handle a case like this.
Reply all
Reply to author
Forward
0 new messages