gpt4 book ai didi

ruby-on-rails - 如何将当前user_id自动添加到另一个表中?

转载 作者:行者123 更新时间:2023-12-02 15:26:59 26 4
gpt4 key购买 nike

我一直在研究模型。

我正在使用设计

我的模式:

  create_table "complaints", force: :cascade do |t|
t.string "title"
t.text "complaint_info"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end

add_index "complaints", ["user_id"], name: "index_complaints_on_user_id", using: :btree

create_table "users", force: :cascade do |t|
...
end

投诉模式:

class Complaint < ActiveRecord::Base
belongs_to :user

validates :title, presence: true
end

用户模型:

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

has_many :complaints
end

我假设这是 Rails 的设置,假设 current_user id 进入 user_id 但它没有存储它,我必须像这样在 Controller 中手动完成:

def create
@complaint = Complaint.new(complaint_params) do |c|
c.user_id = current_user.id
end

if @complaint.save
redirect_to dashboard_complaint_path(@complaint)
else
render 'new'
end
end

private

def complaint_params
params.require(:complaint).permit(:title, :complaint_info)
end

这是正确的做法吗?谢谢。

最佳答案

要让 Rails 自动设置外键,您需要通过父记录关联创建新记录。

@complaint = current_user.complaints.new(complaint_params)

关于ruby-on-rails - 如何将当前user_id自动添加到另一个表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29858929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com