Ruby on rails 当我添加了很多数据时,有些数据突然没有保存

Ruby on rails 当我添加了很多数据时,有些数据突然没有保存,ruby-on-rails,associations,has-many,Ruby On Rails,Associations,Has Many,我有3个模型,挑战,双关,用户(由Clearance gem管理) 用户可以创建挑战。挑战包含许多双关语。用户还可以创建双关语 一切都很好,直到我将双关语设置为属于某个用户,然后突然双关语不再保存 class User < ApplicationRecord include Clearance::User has_many :challenges has_many :puns end class Challenge < ApplicationRecord has_m

我有3个模型,挑战,双关,用户(由Clearance gem管理)

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

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

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
我做错了什么?我试图让它尽可能简单,但似乎用户不希望与多个事物关联,尤其是嵌套的。这是清关问题吗

数据库设置:

  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

在当前代码中,设置用户id后不会保存它。如果您不希望创建失败,您可以执行“创建!”。 因此,您可以尝试:

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

  redirect_to @challenge
end

您只需使用表单中的
hidden_字段
即可完成此操作

<%= object.hidden_field :user_id, value: current_user.id %>
和重定向

redirect_to @pun
它会起作用的

@pun.user_id = current_user.id if current_user
redirect_to @pun