【发布时间】: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