gpt4 book ai didi

ruby-on-rails - ActiveRecord find_or_build_by

转载 作者:数据小太阳 更新时间:2023-10-29 06:49:27 24 4
gpt4 key购买 nike

我想执行:

    XXX.find_or_build_by_language_id(attributes)

我找到了

    XXX.find_or_initialize_by_language_id(attributes)

但这只设置了 language_id 而没有其他属性。即使我手动设置属性,当我执行XXX.save 时记录也不会被保存。

我刚刚读了Rails - find or create - is there a find or build? ,这似乎与我的问题有关,但不符合我的需要。

编辑

让我们使用这个场景

# db/migrations/create_models.rb
class CreateModels < ActiveRecord::Migration
def self.up
create_table :companies do |t|
t.string :name
end

create_table :employees do |t|
t.string :name
t.string :city
t.references :company
end
end
end

-

# app/models/employee.rb
class Employee < ActiveRecord::Base
belongs_to :company
end

-

# app/models/company.rb
class Company < ActiveRecord::Base
has_many :employees
end

-

# rails console
:001> c = Company.new
=> #<Company id: nil, name: nil>
:002> c.employees
=> []
:003> e = c.employees.find_or_initialize_by_name(:name => 'foo', :city => 'bar')
=> #<Employee id: nil, name: "foo", city: "bar", company_id: nil>
:004> c.employees
=> []
:005> c.save
=> true
:006> c.employees
=> []
:007> e.save
=> true
:008> c = Company.first
=> #<Company id: 1, name: nil>
:009> c.employees
=> [#<Employee id: 1, name: "foo", city: "bar", company_id: 1>]
:010> e = c.employees.find_or_initialize_by_name(:name => 'foo', :city => 'baz')
=> #<Employee id: 1, name: "foo", city: "bar", company_id: 1>
:011> e.city = 'baz'
=> "baz"
:012> c.employees
=> [#<Employee id: 1, name: "foo", city: "bar", company_id: 1>]
:013 > c.save
=> true
:014> c.employees
=> [#<Employee id: 1, name: "foo", city: "bar", company_id: 1>]

问题

  1. :004 => 来自:003 的员工未添加到 c.employees
  2. :006 => 来自:003 的员工用 c 保存
  3. :010 => 员工城市属性未设置
  4. :014 => 保存公司时员工的城市属性没有更新

最佳答案

这个怎么样?

employee_attrs = {:name => 'foo', :city => 'bar'}
e = c.employees.where(employee_attrs).first || c.employees.build(employee_attrs)

关于ruby-on-rails - ActiveRecord find_or_build_by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6833663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com