Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 find_or_create_by

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
like image 523
leonel Avatar asked Oct 10 '22 20:10

leonel


1 Answers

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.

like image 190
Tilo Avatar answered Oct 13 '22 09:10

Tilo