Rails 5、更新控制器中的特定表单字段

Rails 5, updating specific form fields in controller

我有管理员帐户可以编辑来自其他用户的一些 posts,主要是拼写错误的东西。当我使用下面的控制器时,它会更新 user_id,因为我是从 current_user(在我的例子中是管理员)那里得到的,所以它会用我的帐户更新 post,并且 post看起来像是我提交的。它会覆盖实际的用户 ID。

  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

顺便说一句,这是我的 _form.html.erb,用于新建和编辑。

<%= simple_form_for(@post) do |f| %>
  <%= f.error_notification %>

    <%= f.input :user_id, input_html: { value: current_user.id }, as: :hidden  %>
    <%= f.input :title, required: true, autofocus: true, placeholder: "Post title: *", label: false, input_html: { maxlength: 140, size: 40 } %>
    <%= f.input :link, required: true, placeholder: "Post link: *", label: false, input_html: { maxlength: 300, size: 40 } %>
    <%= f.input :description, placeholder: "Summary of the Post", label: false, input_html: { maxlength: 600, :rows => 5 } %>

    <%= f.button :submit, "Post" %>
<% end %>

和我的架构

  create_table "posts", force: :cascade do |t|
    t.string "title"
    t.string "link"
    t.text "description"
    t.integer "user_id"
    t.string "slug"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["slug"], name: "index_posts_on_slug"
    t.index ["user_id"], name: "index_posts_on_user_id"
  end

如何跳过更新 user_id? 我试图在下面编写代码来定义我想要更新的字段,但它不起作用。谢谢

if @post.update(post_params[:title, :link, :description])

试试这个,谢谢!

@post.title = post_params[:title]
@post.link = post_params[:link]
@post.description = post_params[:description]

将其放在respond do之前并将if @post.update(post_params)替换为if @post.save