jordan
jordan

Reputation: 10812

Rails 4 - Prepopulating a new record from another Model

I have two models: Bid and Template. Each new bid that is created, needs to prepopulate some attributes with values from attributes of an existing Template instance. First, would I do this in the controller? That is what I am currently trying to do. My new action looks like this:

(note:I'm using the wicked gem to build the object in steps)

def new
  @bid = Bid.new
  prepopulate(@bid.id)
  redirect_to wizard_path(steps.first, :bid_id => @bid.id)
end

My prepopulate method:

def prepopulate(bid_id)
  @bid = Bid.find(bid_id)
  @template = Template.find(:first)
  @bid.update_attribute(attribute_1: @template.attribute_1)
end

It doesn't update the attributes in the Bid. It doesn't raise any errors either. Is there a better way to accomplish what I'm looking to do? If not, how can I update the attributes from my Template instance?

Upvotes: 0

Views: 176

Answers (1)

BroiSatse
BroiSatse

Reputation: 44715

This is definitively model concern, so it should be moved into your model:

Slightly better way:

Model:

def prepopulate
  template = Template.find(:first)
  attribute_1 = template.attribute_1
end

Controller:

@bid = Bid.new   # create?
@bid.prepopulate

The correct way:

However since you need to do it for every single Bid, just use after_initialize hook method for that:

class Bid < AR::Base
  after_initialize :prepopulate

  private
    def prepopulate
      return unless new_record?
      template = Template.first
      self.attribute_1 = template.attribute_1
    end
  end
end

This approach doesn't require you to do anything in your controller, as simply calling new do all you need.

Upvotes: 4

Related Questions