Rails 3 find_or_create_by
check these write-ups on the ActiveRecord Query Interface for Rails 3.x :
http://guides.rubyonrails.org/active_record_querying.html (see section "15 Dynamic Finders")
http://m.onkey.org/active-record-query-interface
You'll need to create the account first, then the client, then the invoice - otherwise your validations will fail.
It's best to create the client and invoice through their parents, e.g.:
a = Account.find( current_user.account_id )
c = a.clients.create(:name => "new client")
a.save # better "save" than sorry ;-)
c.invoices.create(:invoice_date => Time.now)
c.save
I'd recommend playing around with this in your development database using rails console, so you get a feel for it.
leonel
Updated on June 30, 2022Comments
-
leonel almost 2 years
I'm following http://railscasts.com/episodes/102-auto-complete-association
Everything seems fine. I'm trying to create an invoice and also a client on the fly. It does work. Everything cool.
client belongs_to account invoice belongs_to account invoice belongs_to client
Buuut, both models (Client and Invoice) have a mandatory attribute: account_id.
When I'm trying to create a new client on the fly I get an error
:client_id: - can't be blank
The reason I'm getting this error it's because a Client can't be created because it's requiring an account_id in the Client model. If I remove this line
validates :account_id, :presence => true
in Client model the invoice is added but Client has no account_id.I do have this in clients_controller.rb in the create action to set a default value
@client.account_id = current_user.account_id
invoice.rb
validates :account_id, :presence => true validates :client_id, :presence => true def client_name client.name if client end def client_name=(name) self.client = Client.find_or_create_by_name(name) unless name.blank? end
-
leonel over 12 yearsThe account is already created. The logged in user already has an account_id and can be accessed like this
current_user.account_id
. The problem is getting that very same account_id into the new client record. I'll play around with your code right now. -
leonel over 12 yearsI have this in my invoice model
def organization_name=(name); self.organization = Organization.find_or_create_by_name(name); unless name.blank?; end
The current_user can't be accessed in a model. -
Tilo over 12 yearsif you create the new client record starting from the account record, then it will inherit it's account_id ... see above.