开发者

Rails 3 find_or_create_by

开发者 https://www.devze.com 2023-04-10 17:45 出处:网络
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.

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 i开发者_开发百科s 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号