#ruby-on-rails #parameters #rendering
Вопрос:
Я создаю простое приложение marketplace и использовал simple_forms, чтобы добавить возможность пользователям создавать списки продуктов, которые затем отображаются в таблицах на странице#индекс продукта и могут быть отредактированы, удалены или просмотрены оттуда.
Проблема в том, что, хотя формы будут работать в соответствии с запросом и перенаправлять меня на страницу с индексом продукта#, добавленные мной данные (описание, название, цена, категория), эти параметры не отображаются и остаются пустыми на экране, но в таблице «Мои продукты» занято место.
Пожалуйста, смотрите мой код контроллера ниже:
before_action :set_product, only: %i[ :create, :show, :edit, :update, :destroy ]
helper_method :profile
# GET /products or /products.json
def index
@products = Product.all
end
# GET /products/1 or /products/1.json
def show
@product = Product.find_by(params[:product_id])
end
# GET /products/new
def new
@product = Product.new
end
def seller_id
current_user = Seller.id
end
# POST /products or /products.json
def create
@product = Product.create(params[:product_id])
if @product.save!
redirect_to products_path(@product)
end
end
def update
@product = Product.find_by(product_params[:product_id])
if @product.update(product_params)
redirect_to products_path(@product)
end
end
# DELETE /products/1 or /products/1.json
def destroy
@product = Product.delete(params[:id])
redirect_to products_path
end
private
# Use callbacks to share common setup or constraints between actions.
def params_product
@product = Product.find_by(params[:id])
end
# Only allow a list of trusted parameters through.
def product_params
params.permit(:name, :description, :price, :category, :picture, :buyer_id, :seller_id, :product_id)
end
end```
Product.rb (commented out validations as they kept causing errors):
```class Product < ApplicationRecord
belongs_to :buyer, class_name: "Profile", optional: true
belongs_to :seller, class_name: "Profile", optional: true
has_one :picture
# validates_presence_of :name, presence: true
# validates_presence_of :Description, presence: false
# validates_presence_of :Price, presence: true
# validates_presence_of :Category, presence: true
# validates_presence_of :Picture, presence: true
end```
routes:
```Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :products, only: [:show, :new, :destroy, :create, :update, :index, :edit]
resources :pictures, :image_url
devise_for :users
root 'home#page'
get "/products", to: "products#index"
post "/products", to: "products#create"
get "/products/new", to: "products#new"
get "/products/:id/edit", to: "products#edit"
put "/products/:id", to: "products#update"
get "/products/:id", to: "products#show"
delete "/products/:id", to: "products#destroy"
end
Вид:
-создать
<div class="form-inputs">
<%= f.input :name %>
<%= f.input :Description %>
<%= f.input :Price %>
<%= f.input :Category, collection: ["footwear", "accessories", "menswear", "womenswear"] %>
<%= f.file_field :Picture %>
</div>
<p>
<%= link_to 'Back', products_path %>
</p>
<%end%>
-редактировать
<h1 class="heading">Edit Product</h1>
<div class="form-inputs">
<%= f.input :name %>
<%= f.input :Description %>
<%= f.input :Price %>
<%= f.input :Category, collection: ["footwear", "accessories", "menswear", "womenswear"] %>
<%= f.file_field :Picture %>
<%= link_to 'Submit', product_path, method: :patch %>
</div>
<p>
<%= link_to 'Back', products_path %>
</p>
<%end%>
ИЗМЕНИТЬ: Индексировать html-файл:
<p id="notice"><%= notice %></p>
<h1>Products</h1>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Category</th>
<th>Seller</th>
<th>Actions</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @products.each do |f| %>
<tr>
<td><%= f.name %></td>
<td><%= f.Description %></td>
<td><%= f.Price %></td>
<td><%= f.Category %></td>
<td><%= f.seller_id %></td>
<td><%= link_to 'Show', product_path(f), method: :get %></td>
<td><%= link_to 'Edit', edit_product_path(f), method: :get %></td>
<td><%= link_to "Delete product", product_path(f), method: :delete, data: { confirm: 'Are you sure you want to delete this product?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Product', new_product_path, method: :get %>
</html>
Любая помощь по вышесказанному была бы весьма признательна, так как я новичок в rails.
Комментарии:
1. Проверьте мой ответ ниже. Я перечислил все проблемы.
Ответ №1:
Выпуск 1:
В вашем product_controller
, def create
,
вы создали продукт с @product = Product.create(params[:product_id])
помощью .
Это должно быть @product = Product.create(product_params)
Выпуск 2:
В вашем коде слишком много несоответствий. В продукте _form
вы использовали Description
(верхний D
), но в контроллере product_params вы разрешаете description
(нижний D
). Проблема заключается в чувствительности к регистру. Не рекомендуется использовать столбцы таблицы с верблюжьим регистром. Держите их в нижнем регистре.
Выпуск 3:
Вы допускаете параметры: params.permit(:name, :description....)
НЕПРАВИЛЬНО!
Правильный путь: params.require(:product).permit(:name, :description....)
Комментарии:
1. К сожалению, я уже пробовал это, и это все еще приводит к отправке форм, но их ввод не отображается, как указано выше.. есть ли что-нибудь еще, что вы могли бы увидеть, что может быть причиной этого?
2. В вашем файле просмотра списка продуктов может возникнуть проблема. Вы можете отредактировать свой ответ и опубликовать как файл представления, так и журналы запросов при отправке формы для создания нового продукта.
3. @SnehaBhamra В вашем коде слишком много несоответствий. В продукте
_form
, который вы использовалиDescription
, но в контроллереproduct_params
, который вы разрешаетеdescription
. Проблема в чувствительности к регистру. Не рекомендуется использовать столбцы таблицы в верблюжьем корпусе. Держите их в нижнем регистре.