Reputation: 1111
I have admin account to edit some posts from other users, mostly typo stuff. When I use the controller below, it updates user_id since I get that from current_user (admin in my case), so it updates the post with my account, and post looks like submitted by me. it overwrites actual 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
btw this is my _form.html.erb which is used both for new and edit.
<%= 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 %>
and my schema
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
How can I skip updating user_id? I tried to code below just to define the fields I wanted to update, but it doesn't work. Thank you
if @post.update(post_params[:title, :link, :description])
Upvotes: 3
Views: 1700
Reputation: 101
Try this instead, thanks!
@post.title = post_params[:title]
@post.link = post_params[:link]
@post.description = post_params[:description]
Put this before respond do
and replace if @post.update(post_params)
to if @post.save
Upvotes: 4