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



我有3个模型,挑战,双关语,用户(由清除宝石管理)

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

一切都很好,直到我设置了一个双关语来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。如果你不希望创造失败,你可以做"创造! 因此,您可以尝试:

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

它会工作

最新更新