如何在控制器创建时添加外键值 [英] How to add foreign key value on controller create

查看:27
本文介绍了如何在控制器创建时添加外键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的数据库,用户可以在其中创建任务.我希望索引页显示哪些用户创建了哪些任务任务和用户之间的关系是一个用户对多个任务.该任务有一个 user_id 外键.用户只有通过 Devise 登录后才能创建任务.

I have a simple database where users can create a task. I would like the index page to show which users created which task The relationship between task and user is 1 user to many tasks. The task has a user_id foreign key. Users can only create a task when they are logged in via Devise.

我的创建控制器如下,但我不知道如何记录该任务的外键,即创建它的用户.

My create controller is as follows but I don't know how to record the foreign key for that task i.e. the user that created it.

def create
    @challenge = Challenge.new(challenge_params)

    respond_to do |format|
      if @challenge.save
        format.html { redirect_to users_path, notice: 'Challenge was successfully created.' }
        format.json { render :show, status: :created, location: @challenge }
      else
        format.html { render :new }
        format.json { render json: @challenge.errors, status: :unprocessable_entity }
      end
    end
  end

推荐答案

那么你应该:

@challenge = Challenge.new(challenge_params.merge({user_id: current_user.id}))

这篇关于如何在控制器创建时添加外键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆