[英]Error when creating new record of Model in Rails 5
我的rails應用程序中有2個模型。 用戶和目標。 我將它們設置為:
用戶模型
class User < ApplicationRecord
has_one :goal, dependent: :destroy
end
目標模型
class Goal < ApplicationRecord
belongs_to :user, optional: true
end
每當我嘗試對目標模型進行新記錄時,都會出現此錯誤:
undefined method `new' for nil:NilClass
這是我的控制器和目標模型的視圖
目標控制者
class GoalsController < ApplicationController
def index
end
def new
@goal = Goal.new
end
def create
@goal = current_user.goal.new(goal_params)
if @goal.save
redirect_to @goal
else
render 'new'
end
end
private
def goal_params
params.require(:goal).permit(:user_id, :goal_type)
end
end
目標視圖(新操作)
<%= form_for(@goal) do |f| %>
<div class="field">
<%= f.label :goal_type, "Would you like to..." %>
<%= f.select :goal_type, ["Loose weight", "Gain weight", "Keep current weight"] %>
</div>
<div class="field submit">
<%= f.submit "Submit", class: "button button-highlight button-block" %>
</div>
<% end %>
在我的目標表中,有一列goal_type和user_id。 我需要這樣做,以便在創建新記錄時,user_id字段會自動用current_user id填充(當然是通過設計)。
提前致謝!
我只是將控制器從:
@goal = current_user.goal.new(goal_params)
至:
@goal = current_user.build_goal(goal_params)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.