Module: CodyRobbins::CreateNew::InstanceMethods

Defined in:
lib/cody_robbins/create_new/instance_methods.rb

Instance Method Summary collapse

Instance Method Details

#create_new(name) ⇒ Object

Creates a new instance of an ActiveRecord model and assigns it to an instance variable.

  • You pass the name of the model to create to the method.
  • The key in params assumed to contain the attributes of the model is extrapolated from the model name. For example, if the model is User then this key would be :user.
  • The instance variable that the new instance is assigned to will be named according to the model. For example, if the model is User then the instance variable will be @user.

Examples:

The following two actions are equivalent.


class UserController < ApplicationController
  # The usual Rails way.
  def create
    @user = User.new(params[:user])
  end

  # Using create-new.
  def create
    create_new(:user)
  end
end

Parameters:

  • name (Symbol, String)

    The name of the model to create.

Returns:

  • Returns the new instance of the model.



26
27
28
29
30
31
32
# File 'lib/cody_robbins/create_new/instance_methods.rb', line 26

def create_new(name)
  model = name.to_class
  attributes = params[name]
  object = model.new(attributes)

  set_instance_variable(name, object)
end