如何保存需要彼此存在的两个模型

时间:2019-07-08 18:09:46

标签: ruby-on-rails ruby associations

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

在创建帐户时,会为用户创建一个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

1 个答案:

答案 0 :(得分:0)

has_one has_many 关联的 build方法语法不同。

invalid_grant

has_many关联的语法:

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_one关联的语法:

user.messages.build

有关详细信息,请阅读has_one关联documentation