帮忙。我不知道我是怎么得到这个错误的。我正在尝试为用户创建配置文件。该错误似乎来自我对配置文件的创建操作。它看起来不错,但显然它不是
尝试创建时出现错误:
undefined method `build_profile' for #<Profile:0x5ffcca0>
app/controllers/profiles_controller.rb:27:in `create'
配置文件控制器:
class ProfilesController < ApplicationController
before_action :authenticate_user!
before_action :set_profile, only: [:show, :edit, :update, :destroy]
def index
@profiles = Profile.all
end
def edit
@profile = Profile.find(params[:id])
end
def show
@profile = Profile.find(params[:id])
end
def new
@profile = Profile.new
@profile.first_name = current_user.first_name
@profile.last_name = current_user.last_name
@profile.account_type = current_user.account_type
@profile.email = current_user.email
end
def create
@profile = Profile.new(profile_params)
if @profile.save
redirect_to root_path
else
render 'new'
end
end
def update
@profile = Profile.find(params[:id])
if @profile.update(profile_params())
flash[:sucess] = "Sucessfully updated"
redirect_to profile_path(@profile.id)
else
flash[:error] = "Error" # Optional
render "profiles/edit"
end
end
def destroy
@profile = Profile.find(params[:id])
@profile.destroy!
redirect_to "/profiles/show"
end
# Never trust parameters from the scary internet, only allow the white list through.
def profile_params
params.require(:profile).permit!
end
end
个人资料模型:
class Profile < ActiveRecord::Base
belongs_to :user
before_create :build_profile
end
个人资料的架构
create_table "profiles", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "username"
t.string "gender"
t.date "birthday"
t.string "email"
t.string "account_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "handedness"
t.string "coach"
t.date "date_joined"
t.integer "year"
t.string "course"
t.string "main_weapon"
t.string "additional_weapon"
t.integer "cellphone_number"
t.integer "emergency_contact"
t.string "contact_name"
t.string "contact_rel"
t.string "player_status"
t.integer "user_id"
end
答案 0 :(得分:1)
方法build_profile
不在您的Profile
课程中(例如Model
),但您通过before_create
回调来调用它:
class Profile < ActiveRecord::Base
belongs_to :user
before_create :build_profile
end
你需要在课堂上定义build_profile
(或者从其他地方包括它,如module
):
class Profile < ActiveRecord::Base
belongs_to :user
before_create :build_profile
private
def build_profile
# method code...
end
end