如何使用嵌套路线创建评论表单? (/:用户名/帖子/:post_id /评论)

时间:2019-06-13 09:27:03

标签: ruby-on-rails-5 form-for

这是我的第一个Rails应用。我正在尝试创建一个包含用户,帖子和评论的博客。我已经创建了用户和帖子,但是在使我的评论表正常工作时遇到了一些麻烦。我正在使用form_for助手,并且我的评论嵌套在:username范围和帖子资源中。我不断收到错误消息:

  

没有路由匹配{:action =>“ index”,:controller =>“ comments”,:id =>“ 1”,:username =>#},缺少必需的键:[:post_id]

似乎没有从current_user中找到用户名或从帖子中找到post_id。我已经检查了schema.rb,并且posts表中有一个post_id列。我很确定我只是打错了电话。

我的评论表单: app / views / comments / _form.html.erb

<h3> Add Comment </h3>
<%= form_for([@post, @post.comments.build]) do |f| %>
  <%= f.error_messages %>

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

routes.rb

Rails.application.routes.draw do
    root 'sessions#new'

    resources :users

    resources :sessions, only: [:new, :create, :destroy]

    scope ':username' do
    resources :posts, except: [:create] do
      resources :comments
      end
    end

    scope ':username' do
    resources :admin, only: [:index]
    end

    post '/:username/posts', to: 'posts#create', as: 'user_posts'
    get 'signup', to: 'users#new', as: 'signup'
    get 'login', to: 'sessions#new', as: 'login'
    get 'logout', to: 'sessions#destroy', as: 'logout'
    get '/:username/admin', to: 'admin#index', as: 'admin'

end

user.rb

class User < ApplicationRecord
  has_many :posts

  has_secure_password

  validates :email, presence: true, uniqueness: true

  has_one_attached :avatar

end

post.rb

class Post < ApplicationRecord
belongs_to :user
has_many :comments

end

comment.rb

class Comment < ApplicationRecord
  belongs_to :post
end

posts_controller.rb

class PostsController < ApplicationController

  def index
    @posts = Post.all
  end

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

  @comment = @post.comments.new
  end

  def new
    @post = Post.new

  end

  def create
    @post = current_user.posts.new(post_params)
    if (@post.save)
      redirect_to posts_path
    else
      render 'new'
    end
  end

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

  end

  def update
    @post = Post.find(params[:id])
    if (@post.update(post_params))
      redirect_to post_path(current_user.username, @post)
    else
      render 'edit'
    end
  end

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

    redirect_to posts_path
  end

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

comments_controller.rb

class CommentsController < ApplicationController
  def new
    @comment = Comment.new
  end

  def create
    @post = current_user.post.find(params[:id])
    @comment = @post.comments.build(comment_params)
    redirect_to user_post_path(@post)
  end

  private
  def comment_params
    params.require(:comment).permit(:username, :body)
  end
end

0 个答案:

没有答案