正在删除 rails 中的 posts/questions

Deleting posts/questions in rails

我是初学者,正在学习 rails 教程。我被指派为 create/view/index 提出的所有问题创建问题模型和控制器。我还需要能够删除问题。我对控制器中需要什么有了一些想法 here,但我不确定如何在视图中实现该功能。我想在编辑页面中包含删除问题的选项。任何指点将不胜感激——非常感谢!

我的控制器:

class QuestionsController < ApplicationController
  def index
    @questions = Question.all
  end

  def new
    @question = Question.new
  end

  def create
    @question = Question.new(params.require(:question).permit(:title, :body))
    if @question.save
      flash[:notice] = "Question was saved."
      redirect_to @question
    else
      flash[:error] = "There was an error saving the post. Please try again."
      render :new
    end 
  end

  def show
    @question = Question.find(params[:id]) 
  end

  def edit
    @question = Question.find(params[:id])
  end

  def update
    @question = Question.find(params[:id])
    if @question.update_attributes(params.require(:question).permit(:title, :body))
      flash[:notice] = "Question was updated"
      redirect_to @question
    else
      flash[:error] = "There was an error saving your post. Please try again."
      render :edit
    end
  end

  def destroy
    @question = Question.find(params[:id])
    @question.destroy
    redirect_to questions_path
    flash[:notice] = "The question has been deleted."
  end
end

显示视图:

<h1><%= @question.title %></h1>

<%= link_to "Edit", edit_question_path(@question), class: 'btn btn-success' %>

<p><%= @question.body %></p>

编辑视图:

<h1>Edit and Update Question</h1>

<div class="row">
  <div class="col-md-4">
    <p>Guidelines for questions</p>
    <ul>
      <li>Stay on topic.</li>
    </ul>
  </div>
  <div class="col-md-8">
    <%= form_for @question do |f| %>
      <div class="form-group">
        <%= f.label :title %>
        <%= f.text_field :title, class: 'form-control', placeholder: "Enter post title" %>
      </div>
      <div class="form-group">
        <%= f.label :body %>
        <%= f.text_area :body, rows: 8, class: 'form-control', placeholder: "Enter post body" %>
      </div>
      <div class="form-group">
        <%= f.submit "Save", class: 'btn btn-success' %>
      </div>
    <% end %>
  </div>
</div>

你走在正确的轨道上。要在 index 视图(未显示?)中包含删除 link,您可以使用 link_to:

  <%= link_to "delete", @question, method: :delete,
                                   data: { confirm: "Are you sure?" } %>

其中 @question 表示您 index 视图中的问题之一。