编辑帖子/产品时,如何获取它以记住类别(我不必重新选择它)?
问题描述:
当我在我的Rails 5应用程序中创建新列表(新产品发布)时,我通过下拉菜单选择一个类别,例如电子产品,家居装修等。如果创建项目后返回并编辑它,我有再次选择一个类别,否则它将不再拥有一个类别。当我去编辑时,如何告诉该类别被记住或预先填充?可能很容易对非noob ...谢谢!编辑帖子/产品时,如何获取它以记住类别(我不必重新选择它)?
这是窗体上的类别输入字段:
<div class="field">
<%= f.label :category %>
<%= select_tag(:category_id, options_for_select(Category.all.map{|c| [ c.name, c.id]}), :prompt => "Select one!") %>
我不知道我应该张贴别的什么,所以这里的类控制器代码:
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update, :destroy]
def index
@categories = Category.all
end
def show
end
def new
@category = Category.new
end
def edit
end
def create
@category = Category.new(category_params)
respond_to do |format|
if @category.save
format.html { redirect_to @category, notice: 'Category was successfully created.' }
else
format.html { render :new }
end
end
end
def update
respond_to do |format|
if @category.update(category_params)
format.html { redirect_to @category, notice: 'Category was successfully updated.' }
else
format.html { render :edit }
end
end
end
def destroy
@category.destroy
respond_to do |format|
format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
end
end
private
@category = Category.find(params[:id])
end
def category_params
params.require(:category).permit(:name, :desc)
end
end
DB中的产品表:
create_table "products", force: :cascade do |t|
t.string "name"
t.text "brief"
t.text "description"
t.string "buylink"
t.string "verdict"
t.string "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image"
t.string "youtube"
t.integer "user_id"
t.string "goodverdict"
end
答
说实话。您可以使用通常的脚手架控制器操作。您需要确保您的产品项目具有category_id
的数据库列,并且在您的模型中具有等效关联,例如,
product.rb
has_one :category
category.rb
belongs_to :product
比你products_controller.rb添加category_id
到params
,当它被成功救了它会在你的编辑,以及在你的节目的意见显示。有关更详细的信息,请查看关于R-O-R关联的DOCS。如果您的产品应该有多个类别,您可以选择不同类型的关联。这里的链接: http://guides.rubyonrails.org/association_basics.html
我有,在category.rb:'的has_many:products' 和product.rb,我有'belongs_to的:category' 你是说我需要改变那些你是否推荐或者应该没问题? – Nick
完全没问题,你在数据库中是否也有ID?例如。产品表中的category_id? –
是的(我在原始问题中粘贴了产品表) – Nick