在Rails 5中创建Model的新记录时出错

问题描述 投票:0回答:1

我的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(当然使用设计)。

提前致谢!

ruby-on-rails database model-view-controller model associations
1个回答
0
投票

我只是改变了控制器:

@goal = current_user.goal.new(goal_params)

至:

@goal = current_user.build_goal(goal_params)
© www.soinside.com 2019 - 2024. All rights reserved.