ruby-on-rails - Rails 5,更新 Controller 中的特定表单字段

标签 ruby-on-rails forms controller ruby-on-rails-5 simple-form

我有管理员帐户可以编辑其他用户的一些帖子,主要是拼写错误的东西。当我使用下面的 Controller 时,它会更新 user_id,因为我是从 current_user(在我的例子中是管理员)那里得到的,所以它会用我的帐户更新帖子,帖子看起来像是我提交的。它会覆盖实际的用户 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

关于ruby-on-rails - Rails 5,更新 Controller 中的特定表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46542130/

相关文章:

javascript - 使用 Jquery .click 显示/隐藏切换,适用于新用户,但不适用于种子

javascript - 保留一份干净的 HTML 元素的副本,以便以后以正确的方式使用 jQuery 进行克隆

grails - 从Grails Controller中的集合中删除空记录

php - (Laravel) 如何从用户模型中获取验证错误?

ruby-on-rails - 如何显示唯一的实例方法?

mysql - 无法从rails连接到远程mysql服务器

ruby-on-rails - Ruby on Rails foreach 与 bootstrap3 行类

php - 在 fancybox 中预览 php/jquery 表单,然后提交或返回表单

java - 从 FXML Controller 中的其他类调用方法

sql - 带有 select_all 的 Rails 准备好的语句