【问题标题】:Create model with it's relations用它的关系创建模型
【发布时间】:2018-04-21 12:50:32
【问题描述】:

我正在尝试将我的项目从 Rails 5.0 迁移到 5.2

项目通过.build_%related_model% 广泛使用相关模型的创建,它在rails 5.0 上工作,现在它已经坏了。 是否删除了此功能,还是应该使用其他语法?

class User < ActiveRecord::Base
  belongs_to :profile, inverse_of: :user
end

class Profile < ActiveRecord::Base
  has_one :user, inverse_of: :profile
end

new_user = User.new
new_user.build_profile
new_user.save

之前这段代码同时创建了User 和他的Profile。现在这将只创建User,而不创建Profile

任何想法如何解决这个问题?

【问题讨论】:

  • 也许您的配置文件模型已经更改了新属性,添加了构建它需要添加的内容?您的个人资料迁移文件是什么?
  • @ImreRaudsepp 模型保存没有任何错误。它只是不保存相关模型。同样,这段代码之前运行良好。
  • 你只更新了 Rails 版本而没有改变任何其他内容,并且它不再工作要明确吗?
  • Gems 和 Ruby 版本也是如此。
  • 尝试检查已构建配置文件的有效性:profile = new_user.build_profile; profile.valid?profile.errors 如果无效

标签: ruby-on-rails ruby-on-rails-5 rails-activerecord


【解决方案1】:
irb(main):001:0> new_user = User.new
=> #<User id: nil, profile_id: nil, created_at: nil, updated_at: nil>
irb(main):002:0> new_user.build_profile
=> #<Profile id: nil, created_at: nil, updated_at: nil>
irb(main):003:0> new_user.save
   (0.1ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "profiles" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2018-04-21 13:16:23.669286"], ["updated_at", "2018-04-21 13:16:23.669286"]]
  Profile Load (0.2ms)  SELECT  "profiles".* FROM "profiles" WHERE "profiles"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  SQL (0.2ms)  INSERT INTO "users" ("profile_id", "created_at", "updated_at") VALUES (?, ?, ?)  [["profile_id", 1], ["created_at", "2018-04-21 13:16:23.691292"], ["updated_at", "2018-04-21 13:16:23.691292"]]
   (181.1ms)  commit transaction
=> true
class CreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      t.integer :profile_id
      t.timestamps
    end
  end
end
class CreateProfiles < ActiveRecord::Migration[5.1]
  def change
    create_table :profiles do |t|

      t.timestamps
    end
  end
end
class User < ApplicationRecord
  belongs_to :profile, inverse_of: :user
end
class Profile < ApplicationRecord
  has_one :user, inverse_of: :profile
end

测试了一切正常。复制代码以回答,因为它在评论中不可读。您的问题一定出在其他地方,您是否收到任何错误或将迁移文件粘贴到有问题的地方

【讨论】:

  • 使用 Rails 5.1.6
【解决方案2】:

accepts_nested_attributes_for :profile 修复了这个确切的问题,但出现了许多其他问题。

我不得不停止此更新并回滚所有内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-15
    • 2016-06-14
    • 2017-07-30
    • 2020-01-27
    • 2017-03-21
    • 2018-06-24
    • 1970-01-01
    • 2019-02-09
    相关资源
    最近更新 更多