3

私は、他のユーザーからの投稿を編集するための管理者アカウントを持っています。以下のコントローラを使用すると、current_user(私の場合はadmin)から取得したuser_idが更新されるため、アカウントに投稿が更新され、投稿されたように見えます。実際のユーザーIDを上書きします。Rails 5、コントローラー内の特定のフォームフィールドを更新する

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]) 
+0

または 'input_htmlにif @post.update(post_params)を置き換える:{値:@のpost.user_id.empty? ? current_user.id:@ post.user_id} ' – Hatik

+0

これは、Nil:NilClassのための未定義のメソッド' user_id 'を返します。新しい投稿のためのものではないのでエラーです。 – Designer

答えて

4

おかげさまでこれを試してください!

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

respond do前にこれを入れて、if @post.save

+0

実際にはどこに行くのですか? @ post.update( "here")に入ることはできません。更新行の前に定義すれば、これをどのように更新に割り当てるのですか?ありがとうございます – Designer

+0

編集された答えをチェックしてください。 –

+0

ああ、それは働いた!しかし、私たちが実際に更新して以来、。 – Designer