Rails 3 find_or_create_by

时间:2011-10-05 18:04:41

标签: ruby-on-rails ruby validation activerecord

我跟随http://railscasts.com/episodes/102-auto-complete-association

一切似乎都很好。我正在尝试创建发票和客户端。它确实有效。一切都很酷。

客户所属_to帐户 发票belongs_to帐户 发票belongs_to客户

Buuut,两个模型(客户和发票)都有一个强制属性:account_id。

当我试图动态创建新客户时,我收到错误:client_id: - can't be blank

我之所以收到此错误是因为客户无法创建,因为客户需要在客户端模型中使用account_id。如果我在客户端模型中删除此行validates :account_id, :presence => true,则会添加发票,但客户端没有account_id。

我在create action中的clients_controller.rb中有这个设置默认值@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

1 个答案:

答案 0 :(得分:4)

在Rails 3.x的ActiveRecord查询接口上查看这些文章:

http://guides.rubyonrails.org/active_record_querying.html(请参阅“15 Dynamic Finders”)

部分

http://m.onkey.org/active-record-query-interface

您需要先创建帐户,然后是客户端,然后是发票 - 否则您的验证将失败。

最好通过父母创建客户和发票,例如:

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

我建议使用rails console在开发数据库中使用它, 所以你能感受到它。