【问题标题】:Rails 5, updating specific form fields in controllerRails 5,更新控制器中的特定表单字段
【发布时间】:2017-10-03 10:09:06
【问题描述】:

我有管理员帐户可以编辑其他用户的一些帖子,主要是拼写错误。当我使用下面的控制器时,它会更新 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])

【问题讨论】:

  • input_html: { value: @post.user_id.empty? ? current_user.id : @post.user_id }
  • 它给出了“nil:NilClass 的未定义方法 `user_id'”错误,因为我相信这不是新帖子的问题

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


【解决方案1】:

试试这个,谢谢!

@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

【讨论】:

  • 它到底去了哪里?它不能进入​​@post.update("here"),如果我们在更新行之前定义,我们如何将它分配给更新?谢谢
  • 哦,成功了!但是既然我们实际上正在更新,为什么 .save 会这样做呢?
  • .save - 如果记录是新的,则在数据库中创建新记录,否则更新现有记录。 Rails 通过检查调用 .save 的记录是否已经存在于数据库中来解决这个问题。在这里查看文档! apidock.com/rails/ActiveRecord/Base/save%21
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多