views:

51

answers:

3

I'm trying to make attributes equal predetermined values, and I'm not sure if I'm doing that efficiently with the following (in my orders controller):

def create
  @order = Order.find(params[:id])
  @order.price = 5.99
  @order.representative = Product.find(params[:product_id]).representative
  @order.shipping_location = SHIPPING_LOCATION
  @order.user = current_user

  respond_to do |format|
   ...
  end
end

Is there a more efficient way to equate attributes in Rails (maybe using models)? If I'm using two different controllers, do I just repeat what I did above for the new controller?

+3  A: 

Use before_create callback in model to assign default values.

Bragi Ragnarson
+3  A: 

Your code is a little off, it looks like a controller action for create, but the code reads like it's for an update.

Regardless... You could use a parameter hash to update everything at once.

In the case where you're creating:

order_update = {:price => 5.99, :representative => 
  Product.find(params[:product_id]).representative, 
  :shipping_location => SHIPPING_LOCATION,
  :user => current_user}

@order = Order.new(order_update)

In the case where you're updating:

@order.update_attributes(order_update) #attempts to save.

Mixing it into your controller code we get:

def create
  @order = Order.find(params[:id])
  order_update = {:price => 5.99, :representative => 
    Product.find(params[:product_id]).representative, 
    :shipping_location => SHIPPING_LOCATION,
    :user => current_user}    

  respond_to do |format|
    if @order.update_attributes(order_update)
      # save succeeded. Redirect.
    else
      # save failed. Render with errors. 
    end
  end
end
EmFi
A: 

Another solution:

class Example < ActiveRecord::Base
  DEFAULTS = HashWithIndifferentAccess.new(:some => 'default', :values => 'here')

  def initialize(params = {})
    super(DEFAULTS.merge(params))
  end
end

Either use initialize and merge with params, or use an ActiveRecord hook like before_create etc.

Thorbjørn Hermansen