Rails 3 find_or_create_by

leo*_*nel 5 ruby validation activerecord ruby-on-rails

我正在关注http://railscasts.com/episodes/102-auto-complete-association

一切似乎都很好.我正在尝试创建一个发票,也是一个客户端.它确实有效.一切都很酷.

客户端belongs_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
Run Code Online (Sandbox Code Playgroud)

Til*_*ilo 4

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

http://guides.rubyonrails.org/active_record_querying.html (请参阅“ 15 动态查找器”部分)

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
Run Code Online (Sandbox Code Playgroud)

我建议您使用 Rails 控制台在开发数据库中尝试一下,这样您就能感受到它。

  • 我的发票模型中有这个 `def Organization_name=(name); self.organization = Organization.find_or_create_by_name(名称); 除非名称.空白?; end` 无法在模型中访问 c​​urrent_user。 (2认同)