【问题标题】:How do I save two models that require the presence of each-other如何保存需要彼此存在的两个模型
【发布时间】:2019-07-08 18:09:46
【问题描述】:

用户属于公会,可以创建和拥有其他人。

创建帐户时,会为用户创建一个 Home 公会,该用户的功能与其他公会不同。

我试过user=User.new ==> user.home.build,但这似乎不起作用。

我不断收到NoMethodError: undefined method 'build' for nil:NilClass

# == Schema Information
#
# Table name: guilds
#
#  id         :bigint           not null, primary key
#  is_home    :boolean          default(FALSE)
#  name       :string           not null
#  owner_id   :integer          not null
#  member_id  :integer          not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Guild < ApplicationRecord
    belongs_to :owner, class_name: :User

    has_many :guild_members, class_name: :User

    # Trying here.
    def self.create_home(user) 
        home = Guild.new(is_home: true, name: user.name, owner_id: user.id ) 
    end
end


# frozen_string_literal: true

# == Schema Information
#
# Table name: users
#
#  id              :bigint           not null, primary key
#  username        :string           not null
#  digits          :integer          not null
#  email           :string
#  password_digest :string           not null
#  session_token   :string           not null
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#  home_id         :integer          not null
#

class User < ApplicationRecord
  has_one :home, class_name: :Guild, foreign_key: :home_id

  belongs_to :guild
end

【问题讨论】:

  • build 方法仅适用于集合。

标签: ruby-on-rails ruby associations


【解决方案1】:

has_onehas_many 关联的 build 方法语法 不同。

class User < ApplicationRecord
    has_one :home, class_name: :Guild, foreign_key: :home_id
    #Let's say user has many messages
    has_many :messages

    belongs_to :guild
end

has_many 关联的语法:

user.messages.build

has_one 关联的语法:

user.build_home  # this will work

user.home.build  # this will throw error

阅读 has_one 关联documentation 了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 2012-07-26
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 2014-09-22
    相关资源
    最近更新 更多