class Question < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :questions
accepts_nested_attributes_for :questions, allow_destroy: true
end
CategoriesController:
private
def category_params
params.require(:category).permit(:title, questions_attributes: [:id, :category_id, :title, :_destroy])
end
在视图中,我有一个显示其所有帖子的类别(CategoriesController#show
)。
每个帖子都是可删除的。
如何通过更新类别构建删除帖子的link_to
帮助器?
答案 0 :(得分:0)
link_to "Remove question", category_path(category, question_attributes(id: question.id, _destroy: true)), method: :put
答案 1 :(得分:0)
= link_to 'Delete question', question, method: :delete, data: {confirm: 'Are you sure?'}
和routes.rb
resources :questions
并在您的控制器中执行必要的操作
class QuestionController < ApplicationController
def delete
question = Question.find(params[:id])
question.category = nil #or whatever you need to do
question.save
end
end
答案 2 :(得分:0)
link_to "Remove question", category_path(category: { questions_attributes: {id: question.id, _destroy: true}}), method: :put
答案 3 :(得分:0)
最好使用控制器中的.delete
collection method完成此操作:
#app/controllers/categories_controller.rb
def delete_question
@category = Category.find params[:category_id]
question = category.questions.find params[:id]
@category.questions.delete question
end
要实现这一点,您需要使用routes
和link_to
这样的帮助:
#config/routes.rb
resources :categories do
patch "question/:id", to: "categories#delete_question" #-> domain.com/categories/15/question/1
end
#app/views/categories/show.html.erb
<% @category.questions.each do |question| %>
<%= link_to "Remove Question", category_question_removal_path(category, question) method: :patch %>
<% end %>