0

これは、「新しい投稿:

フォームの最初の引数に nil を含めたり、空にすることはできません

私のPostController:

class PostsController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]

def index
    @posts = Post.all
end

def show

end

def edit

end

def update
    @post.update(post_params)
    redirect_to posts_path
end

def new
    if user_signed_in?
        @post = Post.new
    else
        flash[:alert] = ":("
    end
end

def create
    @post = Post.new(post_params)
    @post.user_id = current_user.id
    @post.save
    redirect_to posts_path
end

def destroy
    if user_signed_in?
        @post.destroy! 
    else
        flash[:alert] = ":("
    end
    redirect_to posts_path
end


private
def post_params
    params.require(:post).permit(:body)
end

def set_user
    @post = Post.find(params[:id])
end

終わり

および投稿#index:

<% @posts.each do |post|  %>
<%= post.body %>
<%= link_to 'Show', post %>
<%= link_to 'Edit', edit_post_path(post) %>
<%= link_to 'Delete', post, method: :delete %>
<br>


_form.html.erb

<%= form_for(@post) do |f| %>

  <div class="field">
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
4

2 に答える 2

0

devise を使用している場合は、before アクションを追加することでこれを取得できます。

before_action :authenticate_user!, only: [:new]

そして、あなたは次のように新しいアクションを実行します:

def new
  @post = Post.new
end
于 2016-06-02T10:12:21.413 に答える