在 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(当然使用 designise(。

提前感谢!

我刚刚将控制器从:

@goal = current_user.goal.new(goal_params)

自:

@goal = current_user.build_goal(goal_params)

最新更新