我正在尝试在create方法中创建新记录。
用户有很多公寓。
运行此代码时,出现此错误:
NoMethodError (undefined method `apartments' for nil:NilClass): `create'
这是我的控制器的外观:
class ApartmentsController < ApplicationController
# skip_before_action :verify_authenticity_token
def index
@user = User.all
@apartments = Apartment.all
render :json => @apartments, :include => :user
end
def create
# apartment = Apartment.create
# render json: apartment
@apartment = current_user.apartments.build(params[:apartment])
end
def apartment_params
params.require(:apartment).permit(:street_name)
end
结束
这是我的应用程序控制器:
class ApplicationController < ActionController::Base
before_action :authenticate_user!
protect_from_forgery with: :null_session
before_action :configure_permitted_parameters, if: :devise_controller?
def after_sign_in_path_for(resource)
protected_path
end
def after_sign_out_path_for(resource)
root_path
end
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :phone, :hours])
end
结束
我看过其他类似的帖子,但似乎无法解决问题。
此职位的解决方案未提供解决方案: Current_user method using devise
答案 0 :(得分:0)
如果您进行更改,应该会有所帮助:
@apartment = current_user.apartments.build(params [:apartment])
为此:
@apartment = current_user.apartments.create!(params [:apartment])