0

I have controller with action new, and I want it to create ActiveRecord::Base descendant object, and write it into database (without showing it to user).

def new
  active_order = current_user.orders.find {|o| o.status > 0 }
  active_order = Order.new if active_order.nil?
  (...)
end

Order.new creates local object, but my question is -- how to make Rails to fill it with default values and write to database?

2 Answers 2

1

You can write an unsaved ActiveRecord object instance to the database with the save method:

active_order = Order.new if active_order.nil?
active_order.save

It won't fill in the columns automatically, however. If you want to populate it with default values you can do this before calling save:

active_order = Order.new if active_order.nil?
active_order.field_name = "foo"
active_order.save

Or you can pass it in when you call new:

active_order = Order.new(:field_name => "foo") if active_order.nil?
active_order.save

If you want to do something fancier, you can have Rails automatically populate fields when you save by adding something like this to the model:

before_validation_on_create :set_default_values

def set_default_values
  field_name = "foo" if field_name.blank?
end
Sign up to request clarification or add additional context in comments.

1 Comment

A shortcut to active_order = Order.new if active_order.nil? is active_order ||= Order.new .
0

you can use Order.Create(...) which will create a new object and persist it in the database (assuming Order is a child of ActiveBase of course)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.