我在編輯應用程序管理面板中的對象時遇到問題。 (這是一個政治相關的應用程序,因此提及自由黨和保守黨等)。 當我編輯一個類別時,它會創建一個新的類別(具有相同的名稱),而不是更新它。我無法弄清楚爲什麼。 我可以從日誌中看到,當我編輯的類別Rails的出現去POST路線(POST /admin/categories(.:format) admin/categories#create)
而不是PUT或PATCH路線(PATCH /admin/categories/:id(.:format) admin/categories#update)
Rails創建新對象而不是更新它
道歉,如果我使用不正確的術語,我沒有很好地Rails的精通。
categories_controller.rb:
class Admin::CategoriesController < Admin::DashboardController
before_action :find_category, only: [ :edit, :update, :destroy ]
def index
@categories = Category.all
end
def new
@category = Category.new
end
def create
@category = Category.new(category_params)
if @category.save
flash[:notice] = 'Category created'
redirect_to admin_categories_path
else
flash[:error] = 'Something was wrong'
render :new
end
end
def edit
end
def update
@category.update(category_params)
if @article.save
flash[:notice] = 'Category saved'
redirect_to admin_categories_path
else
flash[:error] = 'Something was wrong'
render :edit
end
end
def destroy
@category.destroy
redirect_to admin_categories_path
end
private
def find_category
@category = Category.find(params[:id])
end
def category_params
params.require(:category).permit(:name, :liberal_image, :conservative_image)
end
end
edit.html.slim的管理視圖中(使用苗條):
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true
= javascript_include_tag 'application', 'data-turbolinks-track' => true
.container
= link_to 'Manage Categories', admin_categories_path
h1 = "Edit Category - #{@category.name}"
= render partial: 'form', locals: { category: @category }
= simple_form_for @category, url: admin_category_path, method: 'delete' do |f|
= f.submit 'Delete category', class: 'btn btn-danger btn-lg'
我假定這件事情錯在這些文件中的一個,但讓我知道是否還有其他東西需要複製到那裏。謝謝 !
_form.html.slim
= simple_form_for @category, url: admin_categories_path, method: 'post' do |f|
div.form-group.required
= f.input :name, label: 'Category Name'
div.form-group.required
= f.input :liberal_image, as: :file, label: 'Liberal Image'
div.target
div.form-group.required
= f.input :conservative_image, as: :file, label: 'Conservative Image'
div.target
div.form-actions
= f.submit 'Save', class: 'btn'
javascript:
$(document).ready(function() {
$('input[type="file"]').on('change', function(event) {
var files = event.target.files;
var image = files[0]
var reader = new FileReader();
reader.onload = function(file) {
var img = new Image();
img.src = file.target.result;
$(event.target).parent().parent().find('.target').html(img);
}
reader.readAsDataURL(image);
console.log(files);
});
});
在更新操作中你有'@ article.save',而你可能真正想要的就是'@ category.save' –
你可以在你的問題中顯示部分表單嗎? – SteveTurczyn
@AndreyDeineko我嘗試過,但它仍然在創建一個新的類別。 – boogiewonder