【问题标题】:Rails 3 find_or_create_byRails 3 find_or_create_by
【发布时间】:2011-10-05 18:04:40
【问题描述】:

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

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

客户所属账户 发票所属账户 发票属于客户

但是,两种模型(Client 和 Invoice)都有一个强制属性:account_id。

当我尝试即时创建新客户端时,我收到错误 :client_id: - can't be blank

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

我在创建操作的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

【问题讨论】:

    标签: ruby-on-rails ruby validation activerecord


    【解决方案1】:

    在 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 控制台来解决这个问题, 让你感受一下。

    【讨论】:

    • 帐户已创建。登录的用户已经有一个 account_id,可以像 current_user.account_id 这样访问。问题是将相同的 account_id 放入新的客户记录中。我现在就玩弄你的代码。
    • 我的发票模型中有这个def organization_name=(name); self.organization = Organization.find_or_create_by_name(name); unless name.blank?; end current_user 无法在模型中访问。
    • 如果您从客户记录开始创建新的客户记录,那么它将继承它的account_id ...见上文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    相关资源
    最近更新 更多