当我添加has_many时,有些数据突然没有保存

When I add has_many, some data is suddently not saved

我有 3 个模型,Challenge、Pun、User(由 Clearance 管理 gem)

用户可以创建挑战。挑战包含许多双关语。用户还可以创建双关语。

一切都很好,直到我将双关语设置为 belong_to 一个用户,然后双关语突然不再保存。

class User < ApplicationRecord
  include Clearance::User
  has_many :challenges
  has_many :puns
end

class Challenge < ApplicationRecord
  has_many :puns, :dependent => :delete_all
  belongs_to :user
end

class Pun < ApplicationRecord
  belongs_to :challenge
  belongs_to :user
end

在我的 PunController 中,我尝试建立 current_user id

  def create
    @pun = @challenge.puns.create(pun_params)
    @pun.user_id = current_user.id if current_user
    redirect_to @challenge
  end

  private

  def set_challenge
    @challenge = Challenge.find(params[:challenge_id])
  end

  def pun_params
    params[:pun].permit(:pun_text,:user_id)
  end

我做错了什么?我试图让它尽可能简单,但似乎用户不想与不止一件事相关联,尤其是在嵌套的情况下。这是清关问题吗?

数据库设置:

  create_table "challenges", force: :cascade do |t|
    t.text "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.datetime "start_time"
    t.datetime "end_time"
    t.bigint "user_id"
    t.index ["user_id"], name: "index_challenges_on_user_id"
  end

  create_table "puns", force: :cascade do |t|
    t.text "pun_text"
    t.bigint "challenge_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "user_id"
    t.index ["challenge_id"], name: "index_puns_on_challenge_id"
    t.index ["user_id"], name: "index_puns_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.string "tagline"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "encrypted_password", limit: 128
    t.string "confirmation_token", limit: 128
    t.string "remember_token", limit: 128
    t.index ["email"], name: "index_users_on_email"
    t.index ["remember_token"], name: "index_users_on_remember_token"
  end

嗯,在您当前的代码中,您在设置后不保存 user_id。如果您不希望创建失败,您可以 "create!"。 所以你可以试试:

def create
  @challenge.puns.create!(pun_params.merge(user_id: current_user.id))

  redirect_to @challenge
end

您可以简单地使用 hidden_field 来做到这一点,例如

<%= object.hidden_field :user_id, value: current_user.id %>

没有用户会话将无法工作,因为关系不是可选的,并从控制器中删除此行

@pun.user_id = current_user.id if current_user

并重定向

redirect_to @pun

它会起作用